返回指向成员函数的指针的 C++ 函数

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

提问人:XORer 提问时间:11/1/2023 最后编辑:user4581301XORer 更新时间:11/1/2023 访问量:132

问:

以下工作按预期进行:

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

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

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

但以下内容甚至无法编译:

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)
      |         ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^~

...有什么建议吗?

C++ variadic-templates consteval

评论

1赞 Drew Dormann 11/1/2023
请显示一个产生错误的最小可重现示例。您的“甚至不编译”代码编译并且不生成任何内容
5赞 Ben Voigt 11/1/2023
您将返回指向非静态成员函数的指针,该函数必须在对象上调用。要么将函数设置为静态函数,要么计划在调用该函数时具有该类的实例。
2赞 n. m. could be an AI 11/1/2023
为了调用类的非静态成员函数,您需要一个 类型的对象。中没有这样的对象。你期望这如何工作?TestTestfunctionReturnsFunction2<int, const double>()()
2赞 Jarod42 11/1/2023
应该是 .(Test{}.*functionReturnsFunction2<int, const double>())() == 2
1赞 Raymond Chen 11/1/2023
错误消息似乎很清楚。' 必须使用 '.*' 或 '->*' 调用 '&Test::countNumberOfTypes (...)' 中的成员函数指针' - ' - 您正在尝试调用指向成员函数的指针。'它告诉你你应该写什么。 - 您建议如何改进错误消息?e.g. ‘(... ->* &Test::countNumberOfTypes) (...)’(something->*&Test::countNumberOfTypes)(something)

答:

4赞 Jarod42 11/1/2023 #1

指向成员函数的指针需要 WITH 或 要使用的特殊语法(以及对象)。.*->*

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

或者,您可以使用 std::invoke,它可能具有更常规的语法

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