Is it possible to test if a constexpr function is evaluated at compile time?

前端 未结 6 1970
长情又很酷
长情又很酷 2020-12-14 07:02

Since the extended versions of constexpr (I think from C++14) you can declare constexpr functions that could be used as "real" cons

6条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-14 07:19

    I think the canonical way to do that is with static_assert. static_asserts are evaluated at compile time, so they will break the build if their condition is false.

    #include 
    
    constexpr int foo(const int s) {
      return s + 4;
    }
    
    int main()
    {
        std::cout << foo(3) << std::endl;
        const int bar = 3;
        std::cout << foo(bar) << std::endl;
        constexpr int a = 3;
        std::cout << foo(a) << std::endl;
    
        static_assert(foo(3) == 7, "Literal failed");
        static_assert(foo(bar) == 7, "const int failed");
        static_assert(foo(a) == 7, "constexpr int failed");
        return 0;
    }
    

    clang++ -std=c++14 so1.cpp compiles fine for me, showing that everything works as expected.

提交回复
热议问题