1

I need to pass pointers to member functions as parameters to other functions. I use std::mem_fn to wrap those in function objects.

Sometimes the member functions have overloads. I learned two syntax forms to disambiguate the overloads:

  • To disambiguate template member functions, I use T::template member<template-args> in the pointer-to-member expression.
  • To disambiguate non-template member functions when all overloads are non-template member functions, I pass the function type as explicit template argument to mem_fn: mem_fn<return-type(args-types)>(pointer-to-member-expression).

But what syntax should be used to disambiguate a non-template member function when some overloads are template member functions? My straightforward guess does not compile:

#include <iostream>   // cout
#include <functional> // mem_fn

struct C {
    void f() { std::cout << "f()\n"; }
    void f(int) { std::cout << "f(int)\n"; }

    template <class T>
    void g(T) { std::cout << "g(T)\n"; }
    template <class T1, class T2>
    void g(T1) { std::cout << "g<T1,T2>(T1)\n"; }

    template <class T>
    void h(T) { std::cout << "h(T)\n"; }
    void h(int) { std::cout << "h(int)\n"; }
};

int main() {
    C c;
    // non-template member function vs non-template member function
    std::mem_fn<void()>(&C::f)(c);
    std::mem_fn<void(int)>(&C::f)(c, 1);

    // template member function vs template member function
    std::mem_fn(&C::template g<int>)(c, 1);
    std::mem_fn(&C::template g<int, int>)(c, 1);

    // non-template member function vs template member function
    std::mem_fn(&C::template h<int>)(c, 1);
    // gcc: error: no matching function for call to 'mem_fn<void(int)>(<unresolved overloaded function type>)'
    // clang: error: no matching function for call to 'mem_fn'
    // std::mem_fn<void(int)>(&C::h)(c, 1);

    return 0;
}

See also: https://godbolt.org/z/39dd569cK

FWIW I use C++20 but see the same errors also in C++11.

1
  • 1
    Looks like std::mem_fn is tripping up (in argument deduction). A directly invoked lambda function works fine : [&]{ c.h(1);}(); (see : godbolt.org/z/T1Gjrr8oP) Commented Dec 10, 2024 at 13:13

1 Answer 1

1

You might provide all template parameters:

std::mem_fn<void(int), C>(&C::h)(c, 1);

Demo

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.