首页 > 解决方案 > 重构模板函数中的常量表达式 if 语句

问题描述

我想重构以下代码:

enum Mode { None, Value1, Value2 }
template <Mode mode>
bool func() {
    if (mode == None) {
        helperNone();
        return funcImplNone();
    } else if (mode == Value1) {
        helper1();
        return funcImplValue1();
    } else if (mode == Value2) {
        helper2(); 
        return funcImplValue2();
    }
    return true;
}

因为表达式

mode == None 

在编译期间计算。而且这个代码不会导致代码膨胀(可执行文件中的代码重复)吗?

我正在考虑以下重构:

template<Mode>
bool func() {
    return true;
}

template<>
bool func<None>() {
    return true;
}

template<>
bool func<Value1>() {
    helper1();
    return funcImplValue2();
}

template<>
bool func<Value2>() {
    helper2();
    return funcImplValue2();
}

有没有其他标准的方法来重构它?我们是否保证编译器会优化该代码本身?重构后的代码是不是看起来更清晰了?

标签: c++templatesc++14

解决方案


在这里重构没有什么意义,因为无论如何它都在优化。例如下面的代码只产生一个对 funcImpl(); 的调用。

enum Mode { None, Other };

bool funcImpl();

template <Mode mode>
bool func() {
    if (mode != None)
        return funcImpl();
    return true;
}

void test()
{
    volatile auto a = func<None>();
    a = func<Other>();
}

结果是

test():
    sub     rsp, 24
    mov     BYTE PTR [rsp+15], 1
    call    funcImpl()
    mov     BYTE PTR [rsp+15], al
    add     rsp, 24
    ret

https://godbolt.org/z/V5Uxig


推荐阅读