检查是否存在(重载)成员函数

fox*_*cub 2 c++ templates sfinae c++11

关于检查成员函数是否存在,有许多已回答的问题:例如, 是否可以编写模板来检查函数是否存在?

但是,如果函数重载,此方法将失败.这是一个稍微修改过的代码,来自该问题的最高评价答案.

#include <iostream>
#include <vector>

struct Hello
{
    int helloworld(int x)  { return 0; }
    int helloworld(std::vector<int> x) { return 0; }
};

struct Generic {};


// SFINAE test
template <typename T>
class has_helloworld
{
    typedef char one;
    typedef long two;

    template <typename C> static one test( decltype(&C::helloworld) ) ;
    template <typename C> static two test(...);


public:
    enum { value = sizeof(test<T>(0)) == sizeof(char) };
};


int
main(int argc, char *argv[])
{
    std::cout << has_helloworld<Hello>::value << std::endl;
    std::cout << has_helloworld<Generic>::value << std::endl;
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

这段代码打印出来:

0
0
Run Code Online (Sandbox Code Playgroud)

但:

1
0
Run Code Online (Sandbox Code Playgroud)

如果第二个helloworld()被注释掉了.

所以我的问题是是否可以检查成员函数是否存在,无论它是否过载.

Die*_*ühl 13

在C++中,到目前为止,不可能获取重载集的地址:当您获取函数或成员函数的地址时,该函数要么是唯一的,要么必须选择适当的指针,例如,通过指针直接指向合适的函数或通过强制转换它.换句话说,&C::helloworld如果表达式helloworld不唯一,则表达式失败.据我所知,结果是无法确定可能重载的名称是作为类成员还是作为普通函数出现.

通常,您需要对名称执行某些操作.也就是说,如果知道某个函数是否存在并且可以使用指定类型的一组参数调用就足够了,那么问题会变得很不一样:可以通过尝试相应的调用并在其中确定其类型来回答这个问题.具有SFINAE能力的背景,例如:

template <typename T, typename... Args>
class has_helloworld
{
    template <typename C,
              typename = decltype( std::declval<C>().helloworld(std::declval<Args>()...) )>
    static std::true_type test(int);
    template <typename C>
    static std::false_type test(...);

public:
    static constexpr bool value = decltype(test<T>(0))::value;
};
Run Code Online (Sandbox Code Playgroud)

然后,您可以使用此类型来确定是否存在可以适当调用的成员,例如:

std::cout << std::boolalpha
          << has_helloworld<Hello>::value << '\n'       // false
          << has_helloworld<Hello, int>::value << '\n'  // true
          << has_helloworld<Generic>::value << '\n';    // false
Run Code Online (Sandbox Code Playgroud)