gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-31 02:02:26 26 4
gpt4 key购买 nike

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

由于整数类型隐式转换为 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 重载转换为特化
  • std::enable_if<std::is_same<T, bool>::value, T>::type>关于 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

关于c++ - 尝试使用 sfinae 重载时不需要的 bool 重载替换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57269037/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com