Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking for existence of an (overloaded) member function

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 existence?

But this method fails, if the function is overloaded. Here is a slightly modified code from that question's top-rated answer.

#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;
}

This code prints out:

0
0

But:

1
0

if the second helloworld() is commented out.

So my question is whether it's possible to check whether a member function exists, regardless of whether it's overloaded.

like image 723
foxcub Avatar asked Nov 30 '22 00:11

foxcub


1 Answers

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 <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;
};

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<Hello>::value << '\n'       // false
          << has_helloworld<Hello, int>::value << '\n'  // true
          << has_helloworld<Generic>::value << '\n';    // false
like image 110
Dietmar Kühl Avatar answered Dec 04 '22 14:12

Dietmar Kühl