我一直喜欢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) {
}发布于 2018-07-11 19:14:38
改用非类型模板参数:
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) {
// ...
}这是因为编译器必须替换第一个模板参数,然后才能确定值参数的类型。
发布于 2018-07-11 19:15:35
解决这一问题的一种方法是添加额外的, typename=void参数,这样所有重载都不会有相同数量的模板参数。
https://stackoverflow.com/questions/51292574
复制相似问题