【问题标题】:Signature for function returning a function pointer返回函数指针的函数签名
【发布时间】: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


【解决方案1】:

为了这个目的和更容易理解复杂的表达式存在Clockwise/spiral规则

     +---------------------------------+
     |                                 |
     |       +----------+              |
     |       ^          |              |
bool(*funcReturningFunc2(std::string&))() {}
^    ^                  |              |
|    +------------------+              |
|                                      |
+--------------------------------------+

你可能会问,funcReturningFunc2是什么?

  • funcReturningFunc2 是一个传递对字符串的引用的函数
  • funcReturningFunc2 是一个函数,它传递对返回指针的字符串的引用
  • funcReturningFunc2 是一个函数,它传递对字符串的引用,返回指向函数的指针,不传递任何内容并返回
  • funcReturningFunc2 是一个函数,它传递对字符串的引用,返回指向函数的指针,不传递任何内容并返回 bool

【讨论】:

    【解决方案2】:

    老派的函数指针声明是出了名的难以阅读。

    C++11 为标准库提供了一些类型支持工具,可用于简化复杂的声明,例如

    using ret_t = std::add_pointer_t<bool(std::string&)>;
    using func_ptr_t = std::add_pointer_t<ret_t(std::string&)>;
    

    【讨论】:

      猜你喜欢
      • 2018-08-19
      • 2013-04-10
      • 2018-03-07
      • 2018-11-11
      • 2020-04-29
      • 2013-03-16
      • 2014-10-29
      • 1970-01-01
      相关资源
      最近更新 更多