以下内容按预期工作:
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)
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^~
...有什么建议吗?
指向成员函数的指针需要使用带有
.*
或 ->*
的特殊语法(和对象)。
(Test{}.*functionReturnsFunction2<int, const double>())() == 2)
std::invoke
,它可能具有更常规的语法
(std::invoke(functionReturnsFunction2<int, const double>(), Test{}) == 2)