wal*_*rii 6 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>;
Run Code Online (Sandbox Code Playgroud)
在某些编译条件下,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>;
Run Code Online (Sandbox Code Playgroud)
我转移了自己尝试使用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>;
Run Code Online (Sandbox Code Playgroud)
这仍然生产四种明确的实例,但在那里他们将不会在重复的情况下Type3
是一样的Type1
(除非Type1
是dummy<3>
!)