Why doesn't an if constexpr make this core constant expression error disappear?

前端 未结 3 1131
盖世英雄少女心
盖世英雄少女心 2020-12-05 06:52

In reference to this question. The core constant expression that is used to initialize the constexpr variable y is ill-formed. So much is a given.<

3条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-05 07:30

    The standard doesn't say much about the discarded statement of an if constexpr. There are essentially two statements in [stmt.if] about these:

    1. In an enclosing template discarded statements are not instantiated.
    2. Names referenced from a discarded statement are not required ODR to be defined.

    Neither of these applies to your use: the compilers are correct to complain about the constexpr if initialisation. Note that you'll need to make the condition dependent on a template parameter when you want to take advantage of the instantiation to fail: if the value isn't dependent on a template parameter the failure happens when the template is defined. For example, this code still fails:

    template 
    void f() {
        constexpr int x = -1;
        if constexpr (x >= 0){
            constexpr int y = 1<

    However, if you make x dependent on the type T it is OK, even when f is instantiated with int:

    template 
    void f() {
        constexpr T x = -1;
        if constexpr (x >= 0){
            constexpr int y = 1<();
    }
    

提交回复
热议问题