As far as I can tell the function below is not constexpr, but the code compiles in clang and g++. What am I missing?

后端 未结 2 1566
盖世英雄少女心
盖世英雄少女心 2021-02-14 12:40

I got this example from §5.19/2 in N4140:

constexpr int incr(int &n) {
    return ++n;
}

As far as I can tell, this is not a constexp

2条回答
  •  我寻月下人不归
    2021-02-14 12:58

    As far as I can tell, this is not a constexpr function.

    Why do you say that? The example from §5.19/2 reads:

    constexpr int g(int k) {
        constexpr int x = incr(k); // error: incr(k) is not a core constant
                                   // expression because lifetime of k
                                   // began outside the expression incr(k)
        return x;
    }
    

    incr(k) not being a core constant expression does not mean incr cannot not be a constexpr function.

    Under C++14's constexpr rules, it is possible to use incr in a constexpr context, for example:

    constexpr int incr(int& n) {
        return ++n;
    }
    
    constexpr int foo() {
        int n = 0;
        incr(n);
        return n;
    }
    

    Unless it's downright impossible for the body of the function to be constexpr (for example, calling a non-constexpr function unconditionally), the compiler has no reason to produce an error at the point of definition.

    A constexpr function may even contain paths/branches in the body which would not be constexpr. As long as they are never taken in a constexpr context, you will not get an error. For example:

    constexpr int maybe_constexpr(bool choice, const int& a, const int& b) {
        return choice ? a : b;
    }
    
    constexpr int a = 0;
    int b = 1;
    static_assert(maybe_constexpr(true, a, b) == 0, "!");
    

    live example

提交回复
热议问题