除了预处理器,我如何有条件地启用/禁用显式模板实例化?
考虑:
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(我相信我知道它们失败的原因),但只有预处理器有效(呃)。我正在考虑将类型放入元组或可变参数中,删除重复项,然后使用其余部分进行实例化。
有没有一种方法可以根据模板参数类型有条件地启用/禁用显式模板实例化?
最佳答案
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>;
这仍然会产生四个显式实例化,但在 Type3
的情况下它们不会重复。与Type1
相同(除非 Type1
是 dummy<3>
!)
关于c++ - 条件显式模板实例化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13925730/