条件显式模板实例化

时间:2012-12-18 03:16:12

标签: c++ templates c++11

除预处理器外,我如何有条件地启用/禁用显式模板实例化?

考虑:

template <typename T> struct TheTemplate{ /* blah */ };

template struct TheTemplate<Type1>;
template struct TheTemplate<Type2>;
template struct TheTemplate<Type3>;
template struct TheTemplate<Type4>;

在某些编译条件下,Type3与Type1相同,Type4与Type2相同。发生这种情况时,我收到一个错误。我想检测类型是否相同而不是在Type3和Type4上实例化,如

// this does not work
template struct TheTemplate<Type1>;
template struct TheTemplate<Type2>;
template struct TheTemplate<enable_if<!is_same<Type1, Type3>::value, Type3>::type>;
template struct TheTemplate<enable_if<!is_same<Type2, Type4>::value, Type4>::type>;

我试图改变自己尝试enable_if和SFINAE(我相信我知道他们失败的原因),但只有预处理器工作了(呃)。我考虑将类型放在元组或可变参数中,删除重复项,然后使用余数进行实例化。

有没有办法根据模板参数类型有条件地启用/禁用显式模板实例化?

1 个答案:

答案 0 :(得分:6)

template <typename T> struct TheTemplate{ /* blah */ };

template<int> struct dummy { };

template struct TheTemplate<Type1>;
template struct TheTemplate<Type2>;
template struct TheTemplate<conditional<is_same<Type1, Type3>::value, dummy<3>, Type3>::type>;
template struct TheTemplate<conditional<is_same<Type2, Type4>::value, dummy<4>, Type4>::type>;

这仍会产生四个显式实例化,但在Type3Type1相同的情况下,它们不会重复(除非Type1dummy<3>!)