模板中的enable_if参数创建模板重定义错误
在此答案中,我真正想要做的是定义 typename $ c
In this answer what I really wanted to do is define a typename
in my template parameters which could be used in the cast and return.
这样:
template <typename T>
typename std::enable_if<sizeof(unsigned char) == sizeof(T), unsigned char>::type caster(T value){ return reinterpret_cast<unsigned char&>(value); }
将成为:
template <typename T, typename R = std::enable_if<sizeof(unsigned char) == sizeof(T), unsigned char>::type >
R caster(T value){ return reinterpret_cast<R&>(value); }
这对于单个模板专业化来说是工作和行为,但是我添加了另一个专门化:
This works and behaves as desired for a single template specialization, but say that I add another specialization:
template <typename T, typename R = std::enable_if<sizeof(short) == sizeof(T), short>::type>
R caster(T value){ return reinterpret_cast<R&>(value); }
现在我得到一个错误:
错误C2995:'R caster(T)':函数模板已定义
error C2995: 'R caster(T)' : function template has already been defined
一个方法说服编译器,只有这些专业化中的一个将为任何给定的调用实际构建。
Is there a way to convince the compiler that only one of these specializations will actually build for any given call?
此处的解决方案可能是使用一系列 条件
,这将阻止我不得不使用模板专门化:
It seems that the best solution here may be to use a slew of conditional
s, which would prevent me from having to fool with template specializations:
template <typename T, typename R = std::conditional<sizeof(T) == sizeof(unsigned char),
unsigned char,
conditional<sizeof(T) == sizeof(unsigned short),
unsigned short,
conditional<sizeof(T) == sizeof(unsigned long),
unsigned long,
enable_if<sizeof(T) == sizeof(unsigned long long), unsigned long long>::type>::type>::type>::type>
R caster(T value){ return reinterpret_cast<R&>(value); }
我向读者致歉,因为它像阅读嵌套三元组。但是,我目前不知道一个更干净的方式来处理这个。
My apologies to the reader cause it's like reading nested ternaries. However I'm currently unaware of a cleaner way to handle this.
这可悲的是,仍然不能阻止用户通过提供自己的第二个模板 hvd 提及的参数。
This sadly still doesn't prevent the user from stomping on all my defaulting by providing his own second template parameter as mentioned by hvd.
编辑:
我已提出另一个问题这里有一个不需要放置 typename
在模板定义和中不需要声明该类型两次。
I've asked another question here which has a solution that doesn't require placing the typename
in the template definition and doesn't require declaring the type twice.