Checking for existence of an (overloaded) member function

前端 未结 2 347
后悔当初
后悔当初 2021-01-03 07:48

There are a number of answered questions about checking whether a member function exists: for example, Is it possible to write a template to check for a function's exis

2条回答
  •  悲&欢浪女
    2021-01-03 08:32

    In C++ it impossible [so far] to take the address of an overload set: when you take the address of a function or a member function the function is either unique or it is necessary to have the appropriate pointer be chosen, e.g., by passing the pointer immediately to a suitable function or by casting it. Put differently, the expression &C::helloworld fails if helloworld isn't unique. As far as I know the result is that it is not possible to determine whether a possibly overloaded name is present as a class member or as a normal function.

    Typically you'll need to do something with the name, however. That is, if it is sufficient to know if a function is present and can be called with a set of arguments of specified type, the question becomes a lot different: this question can be answered by attempting a corresponding call and determining its type in a SFINAE-able context, e.g.:

    template 
    class has_helloworld
    {
        template ().helloworld(std::declval()...) )>
        static std::true_type test(int);
        template 
        static std::false_type test(...);
    
    public:
        static constexpr bool value = decltype(test(0))::value;
    };
    

    You'd then use this type to determine if there is a member which can suitably be called, e.g.:

    std::cout << std::boolalpha
              << has_helloworld::value << '\n'       // false
              << has_helloworld::value << '\n'  // true
              << has_helloworld::value << '\n';    // false
    

提交回复
热议问题