我一直很喜欢像这样的函数 SFINAE 语法,似乎通常工作得很好!
template <class Integer, class = typename std::enable_if<std::is_integral<Integer>::value>::type>
T(Integer n) {
// ...
}
但是当我想在同一个班级中也这样做时,我遇到了一个问题......
template <class Float, class = typename std::enable_if<std::is_floating_point<Float>::value>::type>
T(Float n) {
// ...
}
出现如下错误:
./../T.h:286:2: error: constructor cannot be redeclared
T(Float n) {
^
./../T.h:281:2: note: previous definition is here
T(Integer n) {
^
1 error generated.
这些构造函数不应该只针对适当的类型而存在,而不应该同时存在吗?他们为什么会冲突呢?
我这里是不是有点厚了?
另一方面,这确实有效(但我不太喜欢这种语法):
template <class Integer>
T(Integer n, typename std::enable_if<std::is_integral<Integer>::value>::type* = nullptr) {
}
template <class Float>
T(Float n, typename std::enable_if<std::is_floating_point<Float>::value>::type* = nullptr) {
}
使用非类型模板参数代替:
template <class Integer,
std::enable_if_t<std::is_integral<Integer>::value, int> = 0>
T(Integer n) {
// ...
}
template <class Float,
std::enable_if_t<std::is_floating_point<Float>::value, int> = 0>
T(Float n) {
// ...
}
这是可行的,因为编译器必须先替换第一个模板参数,然后才能确定值参数的类型。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)