C/C ++可以"for循环".可以在marco中使用,而不是在"do while"时使用? [英] C/C++ Can "for loop" be used in a marco instead of "do while"?

查看:81
本文介绍了C/C ++可以"for循环".可以在marco中使用,而不是在"do while"时使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设"cond"与程序中的任何名称都不冲突,以下两个构造是否等效?

Are the two below constructions equivalent in assumption that "cond" is not conflicting with any name in the program

#define DOWHILE do { (some_code); } while (0)

#define FORLOOP for(bool cond = true; cond; cond = false) (some_code)

这个问题的目的是:

我有这样的东西

bool printLogs; // nonconstant dynamic variable

我有一个宏(我不能做大的改变,这是一个大项目;我必须处理这个宏)#define LOG ... 就像

And I have a macro(I cannot do big changes, it is a big project; I have to deal with this macro) #define LOG ... which is used like

LOG << "message" << 1 << 0.5 << 'a';

我希望这个宏变成

if (printLogs) {
    PrinterClass() << "message" << 1 << 0.5 << 'a';
}

因此,如果不打印,则不计算打印的参数.在这种情况下,我的解决方法是

So the printed arguments are not calculated if not printed. In this case my solution is

#define LOG for(cond = printLogs; cond; cond = false) PrinterClass()

此解决方案正确吗?还有其他方法吗?

Is this solution correct? Are there any other ways?

更新:很明显,您不能在此处使用简单的if.例如,此代码将无效

UPDATE: Obviouse you cannot use a simple if here. For example this code won't work

#define LOG if(printLogs) PrinterClass()

int main() {
    if (1)
        LOG << 1;
    else
        LOG << 2;
}

更新2:我希望看到有关我或您的解决方案正确性的说明.我必须确保该解决方案不会引起任何问题.您可以在代码中可以插入语句的任何位置插入"do while"构造.因此,"do while"的行为很简单.这对我的建筑是真的吗?

UPDATE 2: I expect to see the explanation of the correctness of my or your solution. I must be sure that solution would not cause any problems. You can insert the "do while" construction anywhere in your code where you can insert a statement. So "do while" behaves as a simple statement. Is that true for my construction?

更新3:带有全局对象的解决方案不能令人满意,因为它将导致巨大的开销

UPDATE 3: The solution with global object does not satisfy as it will cause a huge overhead

#include <atomic>
void printImpl(...);

std::atomic<bool> printLog;

struct Log {
    template <typename T>
    Log& operator<<(const T& t) {
        if (printLog) { 
            printImpl(t);
        }
        return *this;
    }
};

int main() {
   Log() << 1 << 2;
}

所有优化都将变为

int main() {
    if (printLog) {
        printImpl(1);
    }
// Still should check because printImpl could have changed this variable.
// C++ does not provide any way to say "I promise it won't change printLog"
    if (printLog) { 
        printImpl(2);
    }
}

因此,对于<<的每种用法,您都有原子比较.参见 https://godbolt.org/z/sEoUCw

So you have atomic comparison for each use of <<. See https://godbolt.org/z/sEoUCw

推荐答案

您可以这样做:

#define LOG if (!printLogs){} else PrinterClass()

这篇关于C/C ++可以"for循环".可以在marco中使用,而不是在"do while"时使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆