Search code examples
c++templatespointer-to-member

Default value for template with member function pointer


So, I have something like this so far:

struct Foo { int DoNothing() { } };

template<typename T, typename C, typename R>
T Func(C const* obj,
       R (C::*mf)(),
       T* maybe_unused = nullptr)
{
    (obj->*mf)();
    return T{};
}

Foo f;
int r = Func<int>(&f, &Foo::DoNothing); // works as expected

How do I make &Foo::DoNothing() the default for Func(...)? IOW, I would like to pass some other member function of Foo at another time but for the most part, I want DoNothing to be the default. We can safely assume all the member functions I am interested in take no arguments.


Solution

  • How do I make &Foo::DoNothing() the default for Func(...)?

    You basically just specify the required default arguments:

    struct Foo { int DoNothing() const { } };
    
    template<
      typename T, 
      typename C, 
      typename R = decltype(std::declval<const C>().DoNothing())
    >
    T Func(C const* obj,
           R (C::*mf)() const = &C::DoNothing,
           T* maybe_unused = nullptr)
    {
        (obj->*mf)();
        return T{};
    }
    

    Note that you need to specify two different things: for one the default member function to call and additionally the default return value type, as it cannot be deduced from default arguments.