C++ function that returns a pointer to a member function

138 views Asked by At

the following works as expected:

template<typename... Types>
auto countNumberOfTypes() { return sizeof...(Types); }

template<typename... Types>
consteval auto functionReturnsFunction() { return countNumberOfTypes<Types...> };

functionReturnsFunction<int, const double>()() == 2;

but the following does not even compile:

struct Test
{
    template<typename... Types>
    auto countNumberOfTypes() { return sizeof...(Types); }
};

template<typename... Types>
consteval auto functionReturnsFunction2() { return &Test::countNumberOfTypes<Types...>; }

// functionReturnsFunction2<int, const double>()() == 2;

error: must use ‘.*’ or ‘->*’ to call pointer-to-member function in ‘&Test::countNumberOfTypes (...)’, e.g. ‘(... ->* &Test::countNumberOfTypes) (...)’
   29 |     if (functionReturnsFunction2<int, const double>()() == 2)
      |         ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^~

...any suggestions?

1

There are 1 answers

0
Jarod42 On BEST ANSWER

Pointer to member functions requires special syntax with .* or ->* to be used (and an object).

(Test{}.*functionReturnsFunction2<int, const double>())() == 2)

Alternatively, you might use std::invoke which might have more regular syntax

(std::invoke(functionReturnsFunction2<int, const double>(), Test{}) == 2)