C++创建一个类似于 while、if 或 for 的函数
C++ create a function similar to while, if, or for
想想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*
,以foo
、bar
、baz
和构造体。
相关文章:
- Arduino:for/while/if在void setup()或void loop()之前?——错误:之前需要不合格
- 为什么在 C/C++ 中交织 switch/for/if 语句是有效的?
- C++ 访问 if 语句(如果它们在 for 循环中)
- 试图避免在 for 循环中出现 if-else 语句,但代码似乎有一些错误
- 这个 FOR-IF 循环的解释是什么?
- C++ 使用 OpenMP 时,如果 for 循环在 if else 语句中出错
- 如何退出 for 循环内的嵌套 if-else 语句?(C/C++)
- MSVC 和 clang for if constexpr 分支的不同行为
- C++创建一个类似于 while、if 或 for 的函数
- 类似蟒蛇 ||和 &&for if in C++
- R6010 执行后出错.if 语句在 for 循环中.[作业][中止已解决,发现新问题]
- if 语句在 for 循环中不起作用
- 并排使用 for 循环和 if 语句C++
- 仅在向量末尾打印新行 - "if"语句在"for"循环之外
- 使用"for"对"if"进行建模
- 是一个 for 循环,最终甚至不会运行一次,就像调用 if 语句以首先检查大小一样快
- if(a == b) 不适用于 for 循环中的双精度
- 为什么"constructor-way"在"for-loop"允许但不允许"if-statement"声明变量?
- 在C++中,将"if"放在 for 循环之外还是将"if"放在 for 循环中更有效
- 优化代码/实现"for"循环而不是长"if - else if - else"