如何为部分类型名定义函数

时间:2015-02-20 10:16:37

标签: c++ typetraits

我有这样的代码

#include <iostream>

struct X {
};

template <typename T>
struct A {
    static int a();
};

template <>
int A<int>::a() {
    return 42;
}

template <>
int A<X>::a() {
    return 0;
}

int main() {
    std::cout << A<int>().a() << std::endl;
    std::cout << A<X>().a() << std::endl;
    return 0;
}

现在我想为所有算术类型返回42,即std::is_arithmetic<T>::typestd::true_type

我试过

template <typename T, typename U = std::true_type>
struct A {
    static int a();
};

template <typename T>
int A<T, typename std::is_arithmetic<T>::type>::a() {
    return 42;
}

但我收到了以下错误:

a.cpp:12:51: error: invalid use of incomplete type ‘struct A<T, typename std::is_arithmetic<_Tp>::type>’
 int A<T, typename std::is_arithmetic<T>::type>::a() {
                                                   ^
a.cpp:7:8: error: declaration of ‘struct A<T, typename std::is_arithmetic<_Tp>::type>’
 struct A {
        ^

并尝试了

template <typename T>
struct A {
    static int a();
};

template <typename T, typename E = typename std::enable_if<std::is_arithmetic<T>::value>::type>
int A<T>::a() {
    return 42;
}

错误:

a.cpp:12:13: error: default argument for template parameter for class enclosing ‘static int A<T>::a()’
 int A<T>::a() {
             ^
a.cpp:12:13: error: got 2 template parameters for ‘static int A<T>::a()’
a.cpp:12:13: error:   but 1 required

实现这一目标的正确方法是什么?它是否存在?

我知道我可以做到这一点,同时专注于所有结构,但我不希望这样,因为实际上有更多的功能,应该是常见的

1 个答案:

答案 0 :(得分:0)

不,那不行。相反,尝试基于is_arithmetic定义一个包含42或0的单独类型。您可以将boost :: mpl :: if_用于此目的:

template< typename T > struct Res
{
    typedef typename if_<
          std::is_arithmetic<T>
        , static_value<42>
        , static_value<0>
        >::type value;
};