模板模式匹配

Car*_*s00 5 c++ templates c++11

考虑这个类模板:

template <typename T1, typename T2, bool B>
class SomeClass { };
Run Code Online (Sandbox Code Playgroud)

现在,我想提供两个基于B==true和的实现B==false.也就是说,我想说的是:

template <ANYTHING, ANYTHING, true> class SomeClass {
// First implementation
};

template <ANYTHING, ANYTHING, false> class SomeClass {
// Second implementation
};
Run Code Online (Sandbox Code Playgroud)

如何在C++(11)中完成?

pmr*_*pmr 8

部分专业化:

// 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;
Run Code Online (Sandbox Code Playgroud)

我使用了类型包装器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;
Run Code Online (Sandbox Code Playgroud)

有时,您可以使用默认参数中的元编程计算用于部分特化的值:

// primary
template<typename X, typename is_integral_ = std::is_integral<X>::type>
struct Foo;
Run Code Online (Sandbox Code Playgroud)

这使得配置变量可由用户选择覆盖.

struct my {};
Foo<my, std::true_type> x;
Run Code Online (Sandbox Code Playgroud)

为了防止这种情况,通过继承调度:

// primary, where Foo_impl is any of the above
template<typename X>
struct Foo : public Foo_impl<X> {};
Run Code Online (Sandbox Code Playgroud)