隨着偏特:
// 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;
爲了防止這種情況,調度通過繼承:
// primary, where Foo_impl is any of the above
template<typename X>
struct Foo : public Foo_impl<X> {};
來源
2012-11-22 14:59:03
pmr
太棒了!這回答了我的問題。謝謝。你爲什麼使用這個包裝? – Cartesius00
請注意,第一個版本不適用於'Foo>'。我不知道這是否可取。 –
@ R.MartinhoFernandes你的意思是第二個版本,對吧? – pmr