我以前经常使用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: error:'template void::Do()‘不能重载
src/main.cpp:14:18: error: with 'template void::Do()‘void ()
我想禁用enable_if的任何过载,但它不能工作.
知道我今天做错了什么吗?
发布于 2015-07-21 12:37:49
这两个函数具有相同的σ,因此您将得到一个重定义错误。用以下方法尝试它,使用默认参数:
#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>();
}演示
发布于 2015-07-21 12:43:58
另一种编译和工作的语法是将enable_is作为返回类型移动:
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();
}https://stackoverflow.com/questions/31539075
复制相似问题