我有一个结构
template <typename A, typename B>
struct foo {static const int type = 0;};
当 A
和 B
都是算术时,我希望实现有所不同。然而这并没有奏效。
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 specialization和 full 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;};
关于c++ - 多条件模板特化 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55998031/