如何让成员函数实现依赖于 class' 模板参数?
How to have a member function implementation dependent on class' template parameter?
这是我最好的尝试:
#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>'
使用取自父模板的默认参数制作常规模板:
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
}
}
这是我最好的尝试:
#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>'
使用取自父模板的默认参数制作常规模板:
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
}
}