在C ++中编译时条件成员函数调用

在C ++中编译时条件成员函数调用

问题描述:

我有一个模板类,如果模板参数满足某些条件,某些成员函数才有意义。例如,使用 std :: enable_if<> 我可以仅为这些情况定义它们,但是如何有条件地调用它们?这是一个简单的例子

I have a template class for which certain member functions only make sense if the template parameters satisfy certain conditions. Using, for instance, std::enable_if<> I can define them only for these cases, but how can I call them conditionally? Here is a brief example

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?
   }
};


首先,你不能使用SFINAE - 模板类型参数需要在函数而不是类。

Firstly, you can't use SFINAE like that - the template type parameter needs to be on the function, not the class.

完整的解决方案如下所示:

A full solution looks like this:

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"
}