我一直喜欢这样的SFINAE语法功能,似乎一般都运行良好!
template <class Integer, class = typename std::enable_if<std::is_integral<Integer>::value>::type>
T(Integer n) {
// ...
}
Run Code Online (Sandbox Code Playgroud)
但是当我想在同一个班级做同样的事情时,我遇到了一个问题......
template <class Float, class = typename std::enable_if<std::is_floating_point<Float>::value>::type>
T(Float n) {
// ...
}
Run Code Online (Sandbox Code Playgroud)
得到如下错误:
./../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.
Run Code Online (Sandbox Code Playgroud)
这些构造函数不应只存在于适当的类型而且不能同时存在吗?他们为什么会有冲突?
我在这里有点厚吗?
另一方面,这确实有效(但我不喜欢语法):
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) {
}
Run Code Online (Sandbox Code Playgroud)
请改用非类型模板参数:
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) {
// ...
}
Run Code Online (Sandbox Code Playgroud)
这是有效的,因为编译器必须先替换第一个模板参数才能确定value参数的类型.