在调试模式下constexpr函数的compile-time评估

问题描述 投票:0回答:1

#include <stdlib.h>

///////////////////
bool runtimeIsPalindrome(const char* s, int len)
{
  if(len < 2)
    return true;
  else
    return s[0] == s[len-1] && runtimeIsPalindrome(&s[1], len-2);
}

///////////////////
constexpr bool compileTimeIsPalindrome(const char* s, int len)
{
    return len < 2 ? true : s[0] == s[len-1] && compileTimeIsPalindrome(&s[1], len-2);
}

///////////////////
int main()
{
    constexpr char c[] = "helloworlddlrowolleh";
    for(size_t nn=0;nn<1e8; ++nn) {
        // static_assert(compileTimeIsPalindrome(c, sizeof(c)-1 ), "Blah");
        // compileTimeIsPalindrome(c, sizeof(c)-1 );
        // runtimeIsPalindrome( c, sizeof(c)-1 );
    }
}

与版本...
runtimeIsPalindrome

与版本...

clear; g++ -std=c++11 plaindrome.cpp; time ./a.out real 0m8.333s user 0m8.322s sys 0m0.005s
...但是使用

compileTimeIsPalindrome

版本,我实际上似乎观察到一些编译时的魔术...

clear; g++ -std=c++11 plaindrome.cpp; time ./a.out real 0m8.257s user 0m8.247s sys 0m0.004s
为什么在此示例中尝试断言时,汇编时间评估才能起作用?

注:在此示例中进行任何优化的分析似乎毫无意义,因为在循环中调用的函数中,结果似乎是恒定的,从而给出了与上面最快的轮廓时间相似的时间。

	

static_assert(compileTimeIsPalindrome
不能保证编译时间评估,除非在

clear; g++ -std=c++11 plaindrome.cpp; time ./a.out real 0m0.265s user 0m0.263s sys 0m0.001s

,模板参数或任何其他位置中使用的任何其他地方都必须通过语言规则来编译时。 fibonacci系列

constexpr

是一个很好的例子。在使用GCC的我的机器上,对于
c++ c++11 metaprogramming constexpr
1个回答
4
投票
,此GET在编译时进行了评估。对于任何其他参数,允许编译器 - 并且确实确实 - 决定它在计算上太密集,并且默认为运行时评估。


最新问题
© www.soinside.com 2019 - 2025. All rights reserved.