检测constexpr函数的执行时间

时间:2016-03-17 19:22:58

标签: c++ c++11 c++14 constexpr

假设我有这段代码:

#include <iostream>

constexpr int myDumbFunction(int a, bool b);

int main(int argc, char **argv) {

    constexpr auto foo = 0;
    const auto bar         = 0;

    //! compile-time execution:
    std::cout << myDumbFunction(foo, true);

    //! runtime execution:
    std::cout << myDumbFunction(bar, true);

    return 0;
}

constexpr int myDumbFunction(int a, bool b) {
    if(a > 100 and b) {
        return a - 100;
    }
    else if(a < 100 and b) {
        return a + 100;
    }

    return 122;
}

有没有办法检测在编译时是否会调用第一个myDumbFunction()函数调用?

在这个特殊的例子中,它非常明显,但是让我说我​​不知道​​有关我正在传递的物体的所有细节。

另一个constexpr相关问题:是否存在一些不会改变编译时执行的断言?

1 个答案:

答案 0 :(得分:4)

std::cout << std::integral_constant<int, myDumbFunction(foo, true)>::value;
只有在编译时评估myDumbFunction时,

才有效。