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

前端 未结 2 1096
粉色の甜心
粉色の甜心 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 <int N> // pass by value, clang is happy
    void use_size(Foo<N> 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 <int N>
    void use_size(const Foo<N>& foo) {
        auto f = foo;
        constexpr int n = size(f);
    }
    

    Live example

    0 讨论(0)
  • 2021-02-08 11:14

    My interpretation is that clang++ is right and g++ is too permissive.

    We can find a close example ([expr.const] section, page 126) in the standard https://isocpp.org/std/the-standard (draft can be downloaded, attention big PDF! ).

    constexpr int g(int k) { 
        constexpr int x = incr(k); 
    
        return x; 
    }
    

    where it is explained that:

    error: incr(k) is not a core constant expression because lifetime of k began outside the expression incr(k)

    This is exactly what is happening in the use_size() function with the foo argument, even if the size() function only use the N template parameter.

    template <int N>
    constexpr int size(const Foo<N>&) { return N; }
    
    template <int N>
    void use_size(const Foo<N>& foo) { constexpr int n = size(foo); }
    
    0 讨论(0)
提交回复
热议问题