SFINAE没有编译 [英] SFINAE did not compile
问题描述
我以前经常使用SFINAE,但是我有一个非常简单的示例,今天我无法运行。
Very often I used SFINAE before but I have a very very simple example I can't get to run today.
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>();
}
错误:
src / main.cpp:20:18:错误:'template void X :: Do()'无法重载
src/main.cpp:20:18: error: 'template void X::Do()' cannot be overloaded
src / main.cpp:14:18 :错误:使用'template void X :: Do()'
void Do()
src/main.cpp:14:18: error: with 'template void X::Do()' void Do()
我想使用enable_if禁用任何重载,但它并没有工作...
I want to disable any overload with enable_if but it doesn't work...
知道今天我做错了什么吗?
Any idea what today I did wrong?
推荐答案
这两个函数的签名相同,因此会出现重新定义错误。请尝试以下使用默认参数的方法代替:
The two functions have the same sigature, so you get a redefinition error. Try it with the following instead, which uses default arguments:
#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>();
}
这篇关于SFINAE没有编译的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!