How to use 'auto' for declaring a pointer to an overloaded member function?

Viewed 108

If I have an overloaded non-static member function, how can I use auto to declare a pointer for one version of that function?

struct Foo{
   void bar(){}
   void bar(int){}
};

auto ptr = &Foo::bar; // error: unable to deduce 'auto' from '&Foo::bar'
2 Answers

You don't.

Well, you could do an explicit cast to the proper pointer type, but it's really no different from just putting the proper pointer type in place of auto:

using bar_ptr = void (Foo::*)();

bar_ptr ptr = &Foo::bar;

//or

auto ptr = (bar_ptr)&Foo::bar;

You can avoid explicitly mentioning the full type through such a set of functions:

template <class... Params, class R>
    auto ovl(R(*f)(Params...)) {
    return f;
}

template <class... Params, class R, class T>
    auto ovl(R(T::*f)(Params...)) {
    return f;
}

template <class... Params, class R, class T>
    auto ovl_const(R(T::*f)(Params...) const) {
    return f;
}

Usage is as follows, providing the argument types of the targeted function:

auto ptr = ovl<int>(&Foo::bar);

See it live on Wandbox

Overloads for varargs, volatile, ref-qualified, etc. member functions are left as an exercise for the reader.

Related