Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/templates/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 尝试使用sfinae重载时不必要的bool重载替换_C++_Templates_Sfinae_Enable If - Fatal编程技术网

C++ 尝试使用sfinae重载时不必要的bool重载替换

C++ 尝试使用sfinae重载时不必要的bool重载替换,c++,templates,sfinae,enable-if,C++,Templates,Sfinae,Enable If,这个问题的答案几乎完全存在,但我找不到 由于整数类型隐式转换为bool,下面的代码无法正常工作 template <typename T, typename std::enable_if<std::is_integral<T>::value && std::is_signed<T>::value &&

这个问题的答案几乎完全存在,但我找不到

由于整数类型隐式转换为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());
}
模板

内联void test(T){std::cout问题是,对于第一个重载,第二个模板参数(声明为非类型参数)不能被推导,并导致第一个重载

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

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; }
模板
//                                                                                    ^^^

内联无效测试(T){std::cout谢谢你,救了我一天!问题当然是缺少typename=我更喜欢
std::enable_if_T=0
over
typename=std::enable_if_T
:允许其他重载(作为浮点),避免可能的劫持(
test(true)
)。@Jarod42我刚刚修改了它。:)