提问人:XORer 提问时间:11/1/2023 最后编辑:user4581301XORer 更新时间:11/1/2023 访问量:132
返回指向成员函数的指针的 C++ 函数
C++ function that returns a pointer to a member function
问:
以下工作按预期进行:
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)
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^~
...有什么建议吗?
答:
4赞
Jarod42
11/1/2023
#1
指向成员函数的指针需要 WITH 或 要使用的特殊语法(以及对象)。.*
->*
(Test{}.*functionReturnsFunction2<int, const double>())() == 2)
或者,您可以使用 std::invoke
,它可能具有更常规的语法
(std::invoke(functionReturnsFunction2<int, const double>(), Test{}) == 2)
上一个:模板化类型名称的 C++ 模板
评论
Test
Test
functionReturnsFunction2<int, const double>()()
(Test{}.*functionReturnsFunction2<int, const double>())() == 2
e.g. ‘(... ->* &Test::countNumberOfTypes) (...)’
(something->*&Test::countNumberOfTypes)(something)