尝试使用 sfinae 重载时不需要的 bool 重载替换

Unwanted substitution of bool overload when trying to use sfinae overload

这个问题的答案几乎完全一样,但我找不到。

由于整数类型隐式转换为 bool,下面的代码无法正常工作。

template <typename T, typename std::enable_if<std::is_integral<T>::value &&
                                              std::is_signed<T>::value &&
                                              !std::is_same<T, bool>::value, T>::type>
inline void test(T) { std::cout << "int" << std::endl; }

inline void test(bool) { std::cout << "bool" << std::endl; }

int main()
{
    test(int());
    test(bool());
}

为了解决这个问题,我试过了:

但都没有效果(要么是编译错误,要么是两次 bool 调用)。

有什么方法可以将这两个重载分开吗?

问题是,对于第一次重载,声明为非类型参数的第二个模板参数无法推导,并且根本无法进行第一次重载can't be selected

您可以为第二个模板参数指定默认值。例如

template <typename T, typename std::enable_if<std::is_integral<T>::value &&
                                              std::is_signed<T>::value &&
                                              !std::is_same<T, bool>::value, T>::type = 0>
//                                                                                    ^^^
inline void test(T) { std::cout << "int" << std::endl; }

LIVE