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

How do I define function for part of typenames

本文关键字:定义 函数 类型      更新时间:2023-10-16

我有一个类似的代码

#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

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

我知道我可以做到这一点,一次专门化所有结构,但我不想这样,因为实际上还有几个函数,它们应该是常见的

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

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