考虑这个类模板:
template <typename T1, typename T2, bool B>
class SomeClass { };
现在,我想提供两个基于 B==true
和 B==false
的实现。也就是说,我想说的是:
template <ANYTHING, ANYTHING, true> class SomeClass {
// First implementation
};
template <ANYTHING, ANYTHING, false> class SomeClass {
// Second implementation
};
这如何在 C++(11) 中完成?
最佳答案
部分特化:
// primary
template<typename X, typename Bool>
struct Foo;
template<typename X>
struct Foo<X, std::true_type> {};
template<typename X>
struct Foo<X, std::false_type> {};
// use
Foo<X, std::true_type> x;
我为 bool
使用类型包装器,但您也可以使用
非类型模板参数:
// primary
template<typename, bool>
struct Foo;
template<typename X>
struct Foo<X, true> {};
template<typename X>
struct Foo<X, false> {};
// use
Foo<X, true> x;
有时您可以计算用于偏特化的值 在默认参数中使用元编程:
// primary
template<typename X, typename is_integral_ = std::is_integral<X>::type>
struct Foo;
这使得配置变量可以被用户选择覆盖。
struct my {};
Foo<my, std::true_type> x;
为防止这种情况,通过继承进行分派(dispatch):
// primary, where Foo_impl is any of the above
template<typename X>
struct Foo : public Foo_impl<X> {};
关于c++ - 模板模式匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13515300/