我以前经常使用 SFINAE,但我有一个非常非常简单的示例,但今天无法运行。
class X
{
public:
template <typename CHECK, typename = typename std::enable_if< std::is_floating_point<CHECK>::value, void>::type >
void Do()
{
std::cout << "yes" << std::endl;
}
template <typename CHECK, typename = typename std::enable_if< !std::is_floating_point<CHECK>::value, void>::type>
void Do()
{
std::cout<< "no" << std::endl;
}
};
int main()
{
X x;
x.Do<float>();
}
Error:
src/main.cpp:20:18: 错误:'template void X::Do()' 无法重载
src/main.cpp:14:18:错误:使用“模板 void X::Do()”
无效 Do()
我想用enable_if禁用任何重载,但它不起作用......
知道我今天做错了什么吗?
这两个函数具有相同的签名,因此您会收到重新定义错误。请尝试使用以下命令,它使用默认参数:
#include <type_traits>
#include <iostream>
class X
{
public:
template <typename CHECK, std::enable_if_t< std::is_floating_point<CHECK>::value>* =nullptr >
void Do()
{
std::cout << "yes" << std::endl;
}
template <typename CHECK, std::enable_if_t< !std::is_floating_point<CHECK>::value>* =nullptr>
void Do()
{
std::cout<< "no" << std::endl;
}
};
int main()
{
X x;
x.Do<float>();
}
DEMO
另请参阅答案here and here.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)