gpt4 book ai didi

c++ - 优雅地尝试以特定方式执行各种功能

转载 作者:行者123 更新时间:2023-11-28 04:25:00 25 4
gpt4 key购买 nike

我尝试按顺序执行各种函数 n 次,只有在前一个函数没有返回 false(错误)时才继续执行,否则我会重置并重新开始。

一个序列的例子是:

  1. 打开模块:module.power(true),尝试 3 次
  2. 等待信号:module.signal(),尝试 10 次
  3. 发送消息:module.sendSMS('test'),尝试 3 次
  4. 关闭模块:module.power(false),尝试 1 次

这些操作中的每一个都以相同的方式完成,只是更改了 DEBUG 文本和要启动的函数:

DEBUG_PRINT("Powering ON");  // This line changes
uint8_t attempts = 0;
uint8_t max_attempts = 3; // max_attempts changes
while(!module.power(true) && attempts < max_attempts){ // This line changes
attempts++;
DEBUG_PRINT(".");
if(attempts == max_attempts) {
DEBUG_PRINTLN(" - Failed.");
soft_reset(); // Start all over again
}
delay(100);
}
DEBUG_PRINTLN(" - Success");
wdt_reset(); // Reset watchdog timer, ready for next action

有没有一种优雅的方法可以将这个过程放在一个函数中,我可以调用它来以这种特定方式执行所需的函数,例如:

void try_this_action(描述,函数,n_attempts)

这将使上面的操作 1-4 像:

try_this_action("Powering ON", module.power(true), 3);
try_this_action("Waiting for signal", module.signal(), 10);
try_this_action("Sending SMS", module.sendSMS('test'), 3);
try_this_action("Powering OFF", module.power(false), 1);

我遇到的一个困难是调用的函数具有不同的语法(有些带有参数,有些则没有...)。除了在我需要的任何地方复制/粘贴代码块之外,还有更优雅的可调制方式吗?

最佳答案

A difficulty I have is that the functions called have different syntax (some take parameters, some other don't...).

这确实是个问题。随之而来的是,同一函数的实际函数参数可能会有所不同。

Is there a more elegant modulable way of doing this besides copy/paste the chunck of code everywhere I need it ?

我认为您可以制作一个可变参数函数,它使用函数的特定知识进行分派(dispatch),以便处理不同的函数签名和实际参数。不过,我怀疑我是否会认为结果更优雅。

我倾向于通过宏来完成这项工作,而不是:

// desc:     a descriptive string, evaluated once
// action: an expression to (re)try until it evaluates to true in boolean context
// attempts: the maximum number of times the action will be evaluated, itself evaluated once
#define try_this_action(desc, action, attempts) do { \
int _attempts = (attempts); \
DEBUG_PRINT(desc); \
while(_attempts && !(action)) { \
_attempts -= 1; \
DEBUG_PRINT("."); \
delay(100); \
} \
if (_attempts) { \
DEBUG_PRINTLN(" - Success"); \
} else { \
DEBUG_PRINTLN(" - Failed."); \
soft_reset(); \
} \
wdt_reset(); \
} while (0)

用法就像你描述的那样:

try_this_action("Powering ON", module.power(true), 3);

etc.. 虽然效果就好像您确实在每个位置插入了每个 Action 的代码,但使用这样的宏会产生更容易阅读的代码,那就是没有词汇重复。因此,例如,如果您需要更改尝试操作的步骤,您可以通过修改宏来一次性完成。

关于c++ - 优雅地尝试以特定方式执行各种功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54555031/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com