C++创建一个类似于 while、if 或 for 的函数

C++ create a function similar to while, if, or for

本文关键字:if for 函数 while 类似于 创建 一个 C++      更新时间:2023-10-16

想想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(condition) { expression }

是一个函数,而是一个控制结构/一个单独的语言结构;只要condition计算结果为true(即!= 0的东西(,它就会一次又一次地执行expression

相反,形式void myFunction(int someParameter) { expression }的函数定义仅在由另一个函数调用时才执行。

希望它有所帮助;

注意:此解决方案不能保证您的代码审阅者会喜欢它。

我们可以使用类似于Alexandrescu用于他的SCOPE_EXIT宏的技巧(很棒的一小时会议,这个位在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 :/

。在宏展开后重构一个完整的λ,并进入myFunction_detail::operator*,以foobarbaz和构造体。