限制访问功能 [英] Restriction of access to function

查看:139
本文介绍了限制访问功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个泛型类有一个函数,我想限制在浮点类型的实例在编译时。如下例所示:

I have a generic class with a function that I want to restrict to instances of floating point types only, at compile time. As shown in the example below:

template <typename T>
class ClassName
{
    // instance variables, etc..

    void some_method()
    {
        // do stuff, but only for floating point types
    }
}

拒绝使用some_method作为非浮点类型的ClassName?

How do I make the compiler reject the usage of some_method for ClassName of non-floating point types?

我一直在查看SFINAE,但我根本无法使用它,所以几个小时后

I have been looking at SFINAE but I simply can't get it to work, so after several hours of failing I'm asking for your help.

推荐答案

您可以使用 std :: is_floating_point std :: enable_if 的组合仅启用浮点类型:

You can use a combination of std::is_floating_point and std::enable_if to only enable the function for floating point types:

#include <type_traits>

template <typename T>
class ClassName
{
    // instance variables, etc..
 public:
  template<typename T2 = T,
           typename = typename std::enable_if< std::is_floating_point<T2>::value >::type>
  void some_method()
  { 
    // do stuff, but only for floating point types
  } 
};

int main()
{
  ClassName<double> d; // OK
  d.some_method();     // OK
  ClassName<int> i;    // OK
  i.some_method();     // ERROR
}

这篇关于限制访问功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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