【问题标题】:Function, that creates other functions c++ [closed]函数,创建其他函数 c++ [关闭]
【发布时间】:2019-04-26 02:10:23
【问题描述】:

我有一个任务来创建函数 Factory(const std::string name),它返回指向函数的指针,没有打印名称的参数。此外,我应该只使用本机语言方法(没有 lambda 函数等)。可以举个例子吗?

【问题讨论】:

  • “本地语言方法”?你到底是什么意思?此外,要求场外资源是题外话。
  • 嗯 lambda 我称之为“本机语言方法”的东西,因为它是 C++ 语言的一个组成部分。
  • 对于这种 specific 案例,创建一个具有完全符合您要求的函数调用运算符的类并返回其实例(右构造函数,它将使您的 Factor 函数变为单行函数,仅包含合适的 return 语句)。
  • 最后,请阅读how to ask good questions,以及this question checklist。并了解如何创建minimal reproducible example
  • @Blood-HaZaRd Point :-) 我可能应该留下更多未解决的问题。

标签: c++ task function-pointers


【解决方案1】:

您不能在函数中创建函数。唯一的方法是知道那里将出现的所有字符串,并为每个可能的字符串提供一个函数,然后选择并返回正确的函数。否则你可以使用对象:-)

【讨论】:

    【解决方案2】:

    代码中的注释。我故意没有让它直接打印到 std::cout 而是它会返回字符串。随意调整。

    #include <iostream>
    
    struct bork {              // the object to hold the text to return
        std::string text;      // the text to return
    
        // constructor
        bork(const std::string& in) : text(in) {}
    
        // the operator that makes the object behave like a function    
        std::string operator ()(void) const { return text; }
    
        // a factory method to create a "bork"
        static bork make_bork(const std::string& text) {
            return bork(text);
        }
    
    };
    
    int main() {
        auto a = bork::make_bork("howdy");
        auto b = bork::make_bork("world");
    
        std::cout << a() << "\n";
        std::cout << b() << "\n";
    }
    

    【讨论】:

      猜你喜欢
      • 2021-07-30
      • 2018-12-11
      • 2019-01-30
      • 1970-01-01
      • 2021-03-31
      • 2016-07-14
      • 2014-06-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多