0

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?

11
  • 1
    Please show a minimal reproducible example that produces your error. Your "does not even compile" code compiles and doesn't generate anything Commented Oct 31, 2023 at 20:33
  • 5
    You're returning a pointer to a non-static member function, which has to be called on an object. Either make the function static, or plan to have an instance of the class when calling it. Commented Oct 31, 2023 at 20:36
  • 2
    In order to call a non-static member function of class Test, you need an object of type Test. There is no such object in functionReturnsFunction2<int, const double>()(). How do you expect this to work? Commented Oct 31, 2023 at 20:36
  • 2
    Should be (Test{}.*functionReturnsFunction2<int, const double>())() == 2. Commented Oct 31, 2023 at 20:37
  • 1
    Error message seemed quite clear. ` must use ‘.*’ or ‘->*’ to call pointer-to-member function in ‘&Test::countNumberOfTypes (...)’` - ` - you are trying to call a pointer-to-member function. ` e.g. ‘(... ->* &Test::countNumberOfTypes) (...)’ it's telling you what you should have written. (something->*&Test::countNumberOfTypes)(something) - how would you recommend improving the error message? Commented Oct 31, 2023 at 21:16

1 Answer 1

4

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)

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.