Wal*_*ter 1 c++ templates c++11
我有一个模板类,如果模板参数满足某些条件,某些成员函数才有意义.例如,使用std::enable_if<>我只能为这些情况定义它们,但我怎样才能有条件地调用它们?这是一个简短的例子
template<class T> class A
{
typename std::enable_if<std::is_floating_point<T>::value>::type a_member();
void another_member()
{
a_member(); // how to restrict this to allowed cases only?
}
};
Run Code Online (Sandbox Code Playgroud)
首先,你不能像那样使用SFINAE - 模板类型参数需要在函数上,而不是类.
完整的解决方案如下所示:
template<class T> class A
{
private:
template <class S>
typename std::enable_if<std::is_floating_point<S>::value>::type a_member() {
std::cout << "Doing something";
}
template <class S>
typename std::enable_if<!std::is_floating_point<S>::value>::type a_member() {
//doing nothing
}
public:
void another_member()
{
a_member<T>();
}
};
int main() {
A<int> AInt;
AInt.another_member();//doesn't print anything
A<float> AFloat;
AFloat.another_member();//prints "Doing something"
}
Run Code Online (Sandbox Code Playgroud)