代码之家  ›  专栏  ›  技术社区  ›  xmllmx

为什么压缩函数表达式不是主表达式?

  •  0
  • xmllmx  · 技术社区  · 4 月前

    考虑以下代码片段(用clang19编译):

    consteval bool IsEven(int n) {
        return 0 == n % 2;
    }
       
    template<int n>
    requires (IsEven(n)) // ok
    void f1() {}
    
    template<int n>
    requires IsEven(n) // error: Atomic constraint must be of type 'bool'
                       // (found '<overloaded function type>')
    void f2() {}
    

    这个 cppref page 告诉我 IsEven(n) 不是主要表达。我只是想知道:

    为什么是一个consteval函数表达式 不是 主要表达?

    1 回复  |  直到 4 月前
        1
  •  3
  •   user2357112    4 月前

    这与consteval无关。主表达式只是C++语法中表达式的一个句法类别,函数调用不在该类别中。

    需要一个主表达式来避免解析歧义。该标准给出 the following example :

    template<int N> requires N == sizeof new unsigned short
    int f();
    

    如果允许任意表达式,那么约束是否为 N == sizeof new unsigned short 返回类型为 int ,或者约束为 N == sizeof new unsigned 返回类型为 short int .

    语法可能允许一些或所有函数调用表达式没有形式上的歧义,但这样做会使语法复杂化,而不会增加有意义的表达能力——语法应该鼓励使用命名概念,如果你真的想编写一个函数调用,你可以像以前那样把它括在括号里。