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

前端 未结 2 1090
粉色の甜心
粉色の甜心 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: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 
    constexpr int size(const Foo&) { return N; }
    
    template 
    void use_size(const Foo& foo) { constexpr int n = size(foo); }
    

提交回复
热议问题