使用SFINAE检测成员函数

nij*_*sen 9 c++ sfinae c++98

在C++ 11中,要确定某个类是否具有成员函数size,您可以定义以下测试助手:

template <typename T>
struct has_size_fn
{
    typedef char (& yes)[1];
    typedef char (& no)[2];

    template <typename C> static yes check(decltype(&C::size));
    template <typename> static no check(...);

    static bool const value = sizeof(check<T>(0)) == sizeof(yes);
};
Run Code Online (Sandbox Code Playgroud)

是否有类似的技巧在C++ 98中执行此操作而不依赖于编译器扩展,例如typeof

Mat*_* M. 8

实际上,您的检测可能是错误的.

问题是你所检测到的C只有一个成员size:

  • 它可能是一个属性
  • 它可以是任何签名的方法
  • 甚至可能有几种方法(有各种签名)

如果您希望强化检测,您应该尝试仅检测权利 size(无论是什么权利).这是一种强化检测.

template <typename T>
class has_size {
private:
  typedef char Yes;
  typedef Yes No[2];

  template <typename U, U> struct really_has;

  template <typename C> static Yes& Test(really_has <size_t (C::*)() const,
                                        &C::size>*);

  // EDIT: and you can detect one of several overloads... by overloading :)
  template <typename C> static Yes& Test(really_has <size_t (C::*)(),
                                        &C::size>*);

  template <typename> static No& Test(...);

public:
    static bool const value = sizeof(Test<T>(0)) == sizeof(Yes);
};
Run Code Online (Sandbox Code Playgroud)

编辑: 带有重载.

处理错误size成员的技巧是really_has结构.我不假装它是完美的,但......

在C++ 11中,事情变得更简单(虽然并不简单),因为您可以直接使用来检测事物.因此,等效特征是:

template <typename T>
class has_size {
private:
  typedef char Yes;
  typedef Yes No[2];

  template<typename C> static auto Test(void*)
    -> decltype(size_t{std::declval<C const>().size()}, Yes{});

  template<typename> static No& Test(...);

public:
    static bool const value = sizeof(Test<T>(0)) == sizeof(Yes);
};
Run Code Online (Sandbox Code Playgroud)

但是,如果可以的话,C++中推荐的方法不是使用traits ; 例如,在函数中,您可以decltype在类型签名中使用right.