c++ - 多条件模板特化 C++

标签 c++ templates template-specialization

我有一个结构

template <typename A, typename B>
struct foo {static const int type = 0;};

AB 都是算术时,我希望实现有所不同。然而这并没有奏效。

template <typename A, typename B, typename std::enable_if<
        std::is_arithmetic<A>::value && 
        std::is_arithmetic<B>::value, bool>::type = 0>
struct foo<A, B> {static const int type = 1;}

我收到编译器错误默认模板参数可能无法在部分特化中使用。那么我怎样才能做到这一点呢?

要记住的一件事是,我还想要其他更简单的模板特化,可能如下所示。

template <>
struct foo<string, vector<int>> {static const int type = 2;}

总之,我希望第一个定义像默认值一样,然后定义一堆专门的实现,其中一个是通用的。

最佳答案

您可以定义primary template , partial specializationfull specialization分别喜欢

// the primary template
template <typename A, typename B, typename = void>
struct foo {static const int type = 0;};

// the partial specialization
template <typename A, typename B>
struct foo<A, B, typename std::enable_if<
        std::is_arithmetic<A>::value && 
        std::is_arithmetic<B>::value>::type> {static const int type = 1;};

// the full specialization
template <>
struct foo<string, vector<int>, void> {static const int type = 2;};

LIVE

关于c++ - 多条件模板特化 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55998031/

相关文章:

c++ - 如何使用模板函数设置不同类型的值?

c++ - 错误 C2893 : Failed to specialize function template

c++ - 通用对象载体类 - C++

c++ - 模板类可以在不指定其模板参数两次的情况下为自己起别名吗?

c++ - 专用于泛型类模板的类模板

c++ - 为什么C++线程/future开销这么大

c++ - 如何创建一个新线程并在一段时间后终止它?

C++ 模板专门化以提供/添加不同的成员函数

c++ - 根据签名区分专用结构

c++ - 在函数搜索模式中引用二维数组时出错