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

问题描述 投票:0回答:1

以下内容按预期工作:

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个回答
0
投票

指向成员函数的指针需要使用带有

.*
->*
的特殊语法(和对象)。

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

或者,您可以使用

std::invoke
,它可能具有更常规的语法

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

© www.soinside.com 2019 - 2024. All rights reserved.