constexpr expression and variable lifetime, an example where g++ and clang disagree

前端 未结 2 1089
粉色の甜心
粉色の甜心 2021-02-08 10:53

Consider the simple C++11 code:

template
struct Foo {};

template 
constexpr int size(const Foo&) { return N; }

template          


        
2条回答
  •  清歌不尽
    2021-02-08 11:10

    I was expecting Clang to be wrong in this case. It should evaluate your function call as being a constant expression, simply because you use only the template parameter, and not the object itself. Since you don't use the object in your constexpr function, there should be nothing prohibit compile time evaluation.

    However, there's a rule in the standard that says object that began their lifetime preceding the constant expression such as a reference is not useable as constexpr.

    There is a simple fix in that case. I think it didn't like the reference:

    template  // pass by value, clang is happy
    void use_size(Foo foo) { constexpr int n = size(foo); }
    

    Here's a live example

    Alternatively, you can also copy your foo object and use that local object:

    template 
    void use_size(const Foo& foo) {
        auto f = foo;
        constexpr int n = size(f);
    }
    

    Live example

提交回复
热议问题