条件显式模板实例化 [英] Conditional explicit template instantiation
问题描述
除了预处理器之外,我如何有条件地启用/禁用显式模板实例化?
Other than the preprocessor, how can I conditionally enable/disable explicit template instantiations?
请考虑:
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如
Under some compilation conditions, Type3 is the same as Type1 and Type4 is the same as Type2. When this happens, I get an error. I'd like to detect that the types are the same and not instantiate on Type3 and Type4 as in
// 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(我相信我知道他们为什么失败)只有预处理器工作了(ugh)。我正在考虑将类型放在元组或变量中,删除重复的,然后使用剩余的实例化。
I've diverted myself trying enable_if and SFINAE (and I believe I know why they fail), but only the preprocessor has worked (ugh). I'm thinking about putting the types in a tuple or variadic, removing duplicates, and then use the remainder for instantiation.
有条件启用/禁用显式基于模板参数类型的模板实例化?
Is there a way to conditionally enable/disable explicit template instantiation based on template argument types?
推荐答案
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>
!)
This still produces four explicit instantiations, but they won't be duplicates in the case where Type3
is the same as Type1
(unless Type1
is dummy<3>
!)
这篇关于条件显式模板实例化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!