【问题标题】:C++ create a function similar to while, if, or forC++ 创建类似于 while、if 或 for 的函数
【发布时间】:2017-04-11 20:58:27
【问题描述】:

想想用 C/C++ 编写的这段代码:

bool cond = true;
while(cond){
    std::cout << "cond is currently true!";
}

是否可以创建一个可以这样调用的函数?

myFunction(some_parameters_here){
    //Code to execute, maybe use it for callbacks
    myOtherFunction();
    anotherFunction();
}

我知道你可以使用函数指针和 lambda 函数,但我想知道你是否可以。我很确定有办法做到这一点,因为 while() 将如何存在?

【问题讨论】:

  • while 不是函数,而是语言的一部分。您无法使用相同的语法创建函数,但您可以使用 lambda 执行类似的操作,如您所说。
  • 我不确定你在说什么。您是指行为类似于while 的函数吗?通常你会做while (myFunction(args))。较新版本的 C++ 有lambda,但我不确定这是否值得沿着这条路走下去。它可以编写非常复杂的代码。
  • 你也许可以用宏来伪造它。取决于你想让myFunction做什么。
  • goto? (鸭子)
  • @FrançoisAndrieux 通过创造性地使用宏和jmp(又名goto),您可以创建任何您想要的内容。这是一个毫无意义的练习,我同意,而且你当然不能只是随机地向语言中添加新结构。

标签: c++ function lambda


【解决方案1】:

while(condition) { expression } 不是函数,而是控制结构/单独的语言结构;只要condition 评估为true(即!= 0),它就会一次又一次地执行expression

相比之下,void myFunction(int someParameter) { expression } 形式的函数定义只有在被另一个函数调用时才会执行。

希望对你有所帮助;

【讨论】:

  • 我不太确定这是如何回答这个问题的,尽管它确实明确了 while 不是一个函数。但显然确实如此。
【解决方案2】:

注意:此解决方案无法保证您的代码审查员会喜欢它。

我们可以使用类似于 Alexandrescu 为他的SCOPE_EXIT macro 使用的技巧(很棒的一小时会议,这一点是在 18:00)。

它的要点:一个聪明的宏和一个被肢解的 lambda。

namespace myFunction_detail {
    struct Header {
        // Data from the construct's header
    };

    template <class F>
    void operator * (Header &&header, F &&body) {
        // Do something with the header and the body
    }
}

#define myPrefix_myFunction(a, b, c) \
    myFunction_detail::Header{a, b, c} * [&]

如下使用:

myPrefix_myFunction(foo, bar, baz) {

}; // Yes, we need the semicolon because the whole thing is a single statement :/

...在宏扩展后重构一个完整的 lambda,并通过访问 foobarbaz 和构造体进入 myFunction_detail::operator*

【讨论】:

    猜你喜欢
    • 2014-01-16
    • 1970-01-01
    • 2017-02-14
    • 1970-01-01
    • 2018-07-04
    • 1970-01-01
    • 2022-01-13
    • 2012-07-09
    • 1970-01-01
    相关资源
    最近更新 更多