这是我最好的尝试:
#include <iostream>
template <bool EnableSomething = false>
class MyClass
{
typename std::enable_if< EnableSomething >::type
something(int& x)
{
x += 1; //do something
}
typename std::enable_if< !EnableSomething >::type
something(int& x)
{
// do nothing, should be optimized away
}
public:
void Process()
{
int x = 0;
something(x);
std::cout << "Enabled: " << EnableSomething << ". x = " << x << std::endl;
}
};
int main()
{
MyClass<true> yes;
MyClass<false> no;
yes.Process();
no.Process();
return 0;
}
编译器说:
tester.cpp(12): error C2039: 'type': is not a member of 'std::enable_if<false,_Ty>'
答案 0 :(得分:2)
使用从父级tempalte获取的默认参数制作常规模板:
template<bool x_enabled = EnableSomething>
typename std::enable_if< x_enabled >::type
something(int& x)
{
x += 1; //do something
}
template<bool x_enabled = EnableSomething>
typename std::enable_if< !x_enabled >::type
something(int&)
{
// do nothing, should be optimized away
}
使用c ++ 17事情变得更简单:
void
something(int& x)
{
if constexpr(EnableSomething)
{
x += 1; //do something
}
}