【问题标题】:How do I define function for part of typenames如何为部分类型名定义函数
【发布时间】:2015-02-20 10:16:37
【问题描述】:

我有这样的代码

#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&lt;T&gt;::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

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

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

【问题讨论】:

    标签: c++ typetraits


    【解决方案1】:

    不,那是行不通的。相反,请尝试根据 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;
    };
    

    【讨论】:

    • 问题是我希望能够为其他类添加其他值
    • 您可以随意链接 if_s,或者使用其他 MPL 结构。由于“值”是类型,因此这些类型可以实现您想要的任何功能。或者您可以简单地自己提供专门的版本,但是您必须分别为每个整数类这样做。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-06-15
    • 1970-01-01
    • 2010-12-17
    • 2022-08-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多