有条件地包括C ++方式的else子句

时间:2016-05-11 13:30:12

标签: templates c++11

我有一个成员函数,为了调试目的,打印了各种语句。 solve<true>()应该全部打印出来,solve<false>()不应该打印出来。

template <bool print>
void solve() {
    // do a bunch of setup and computations...
    if(print) {// this works as you would expect
        cout << "statistics on various items" << endl;
    }
    // do some more stuff
    for(things i have to do) {
        if(methodCall()) {

        }
        // !!! this is the question !!!
        if(print) {// clearly this isn't valid syntax
        else {
            cout << "only compile else on print=true" << endl;
        }
        }// if(print) end...
    }
}

基本上,methodCall()返回一个布尔值,当它是false时,我不想在模板elsebool时使用false子句if(print) { if(methodCall()) { /// ... } else { /// print stats } } else { if(methodCall()) { /// ... } } 。我明白我能做到

/// ...

但这会非常容易出错,因为if(methodCall())中的代码很大并且正在积极地进行更改。同样,我在这里避免像瘟疫那样的模板专业化......我只需要一个版本的代码来避免复制粘贴错误或不同步更新。 if(methodCall()) { /// ... } #ifdef PRINT_STATS else { cout << "stats" << endl; } #endif 内的内容不起作用,这就是我这样做的原因;)

如果我按照C方式行事

https://example.com/getUser?id=10

但我觉得已经存在C ++替代方案。

如果这不可能,还有替代方案吗?谢谢!

3 个答案:

答案 0 :(得分:3)

你可以这样做:

for(things i have to do) {
    if(methodCall()) {

    }
    else if(print) {
            cout << "only compile else on print=true" << endl;
    }
}

答案 1 :(得分:2)

一个简单的解决方法是拥有专门的帮助模板。

template <bool print> void log() {
   std::cout << "statistics on various items" << std::endl;
}

template <> void log<false> () { }

template <bool print>
void solve() {
    // do a bunch of setup and computations...
    log<print>();
    // ...

答案 2 :(得分:0)

即使在现代C ++中,仍然存在宏的位置,我个人认为这是其中之一。如果是非常标准的做法来定义宏,指定您是否处于调试模式&#39;。

也许这只是个人偏好,但我觉得为此目的使用模板参数是不合适的。该参数没有说明如何评估函数或它对程序状态的影响 - 只是是否应该打印调试语句。这不知道是什么精神&#39;模板