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

前端 未结 3 1533
醉梦人生
醉梦人生 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 05:03

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

    It doesn't. But you are not defining a function constexpr. You are defining a template.

    Let's set up:

    struct Is_constexpr {
      constexpr Is_constexpr() = default;
      constexpr auto bar() {
        return 24;
      }
    };
    
    struct Not_constexpr {
      auto bar() {
        return 24;
      }
    };
    

    Now if you try to define a function (not a template) as constexpr that uses Not_constexpr the compiler won't let you:

    constexpr auto foo_function(Not_constexpr v)
    {
      return v.bar();
      // error: call to non-constexpr function 'auto Not_constexpr::bar()'
    }
    

    You are however defining a template. Let's see how this goes:

    template 
    constexpr auto foo(T v)
    {
      return v.bar();
    }
    

    The compiler lets you do this. No error. Why? Because it's a template. Some instantiations may be constexpr, some not, depending on T:

    int main() {
      constexpr Is_constexpr is_c;
      constexpr Not_constexpr not_c;
    
      std::integral_constant a; // OK
      //std::integral_constant a; // ERROR
    
    }
    

提交回复
热议问题