【发布时间】:2018-02-05 13:48:57
【问题描述】:
我知道在很多情况下最好不要问为什么,但这个函数签名对我来说毫无意义。我知道我们应该使用 typedef,但我想看看我是否能理解如何在没有以下情况下使用:
bool(*fn)(std::string&); // This is function pointer
void funcTakingFunc1(bool(*)(std::string&)) { } // This works for function arguments
bool(*)(std::string&) funcReturningFunc() {} // Trying the same as return type, doesn't work
bool(*funcReturningFunc2(std::string&))() {} // This is what I found on another SO question
我认为最后一个是正确的,这对我来说毫无意义,并且函数名称和“返回函数”的参数从左到右切换。对此有什么解释吗?
具体来说,我正在尝试创建一个接受std::string& 的函数,并返回一个指向bool (*)(std::string&) 的函数指针,但这不起作用:
bool (*getConsoleCmdByName)(std::string&)(std::string& cmd);
编辑:事实证明这是正确的,我认为:
bool (*getConsoleCmdByName(std::string&))(std::string& cmd);
贾罗德建议:
auto getConsoleCmdByName(std::string&) -> bool (*)(std::string&)
作为一种可能性,这对我来说似乎很清楚。
【问题讨论】:
-
bool (*getConsoleCmdByName)(std::string&)(std::string& cmd);->bool (*getConsoleCmdByName(std::string&))(std::string& cmd);Read about the spiral rule。然后忘记它并使用类型别名。 -
您也可以使用该语法(自 C++11 起)
auto getConsoleCmdByName(std::string&) -> bool (*)(std::string&)(与使用 typedef IMO 一样简单)。 -
另外,不要将指针语义隐藏在别名后面,即使对于函数也是如此。定义函数类型别名
using func_type = bool(std::string&);并将指针传递给func_type * fptr = ...; -
啊,我以前讨厌尾随返回类型。
-
顺便说一句,您可能希望传递 const 引用而不是非 const 引用。
标签: c++ function pointers return