在C ++中编译时条件成员函数调用 [英] compile-time conditional member function call in C++

查看:115
本文介绍了在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"
}

这篇关于在C ++中编译时条件成员函数调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆