Why does the C++ compiler makes it possible to declare a function as constexpr, which can not be constexpr?

前端 未结 3 1531
醉梦人生
醉梦人生 2020-12-21 04:00

Why does the C++ compiler makes it possible to declare a function as constexpr, which can not be constexpr?

For example: http://melpon.org/wandbox/permlink/AGwniRNRb

3条回答
  •  星月不相逢
    2020-12-21 04:42

    If you do write this code:

      constexpr int result = reduce(std::plus(), {1, 2, 3, 4, 5, 6, 7});
    

    you will see that reduce doesn't not produce a constexpr result.

    The reason is because "note: non-constexpr function 'accumulate >' cannot be used in a constant expression" And as you can see here - http://en.cppreference.com/w/cpp/algorithm/accumulate

    std::accumulate is not constexpr

    EDIT extending to answer the actual question, thanks @peterchen: It's compiled when it hits the usage, it doesn't and couldn't try and resolve the function until it compiles the specific version of the template. When it hits the usage and triggers the compile, it resolves the accumulate and sees it's not constexpr, so issues an error.

提交回复
热议问题