SFINAE 没有编译
SFINAE did not compile
我以前经常使用 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>();
}
错误:
src/main.cpp:20:18: 错误:'template void X::Do()' 无法重载
src/main.cpp:14:18:错误:'template void X::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>();
}
另请参阅答案 and here。
另一种编译和工作的语法是将 enable_is
移动为 return 类型:
class X
{
public:
template <typename CHECK >
typename std::enable_if< std::is_floating_point<CHECK>::value, void>::type Do()
{
std::cout << "yes" << std::endl;
}
template <typename CHECK>
typename std::enable_if< !std::is_floating_point<CHECK>::value, void>::type Do()
{
std::cout << "no" << std::endl;
}
};
int main()
{
X x;
x.Do<float>();
getchar();
}
我以前经常使用 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>();
}
错误:
src/main.cpp:20:18: 错误:'template void X::Do()' 无法重载
src/main.cpp:14:18:错误:'template void X::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>();
}
另请参阅答案
另一种编译和工作的语法是将 enable_is
移动为 return 类型:
class X
{
public:
template <typename CHECK >
typename std::enable_if< std::is_floating_point<CHECK>::value, void>::type Do()
{
std::cout << "yes" << std::endl;
}
template <typename CHECK>
typename std::enable_if< !std::is_floating_point<CHECK>::value, void>::type Do()
{
std::cout << "no" << std::endl;
}
};
int main()
{
X x;
x.Do<float>();
getchar();
}