代码之家  ›  专栏  ›  技术社区  ›  Brian Vandenberg

“)”标记之前需要主表达式(需要“模板”消歧器)[重复]

  •  0
  • Brian Vandenberg  · 技术社区  · 7 年前

    我有一段类似于以下内容的代码(为了简洁起见,省略了其他细节):

    template <uint First, uint Second, typename T>
    struct Thing {
      std::shared_ptr<T> asdf;
      uint get() const { this->asdf->get_value<First,Second>(); }
    };
    

    。。。在GCC 7中产生以下错误:

    error: expected primary-expression before ')' token
      uint get() const { this->asdf->get_value<First,Second>(); }
                                                             ^
    

    Clang 4.0.1报告没有警告 -Weverything (除了c++98兼容性警告等非常迂腐的东西);GCC 7和 -W{all,extra,effc++,pedantic}


    我之前不知道 this question ;虽然我的问题的答案肯定是在这里概述的,但错误消息并没有明确说明这就是问题所在。假设我删除了这个问题及其关联的答案,其他搜索此错误消息的人只会遇到我找到的问题——也就是说,那些表明问题是由传递类型作为函数参数而不是传递值引起的问题。

    1 回复  |  直到 7 年前
        1
  •  4
  •   Brian Vandenberg    7 年前

    TLDR:解决方案是使用 template 关键字作为 disambiguator (at the bottom of the page) 呼叫时 get_value<A,B>() :

    uint get() const { auto tmp = this->asdf->template get_value<First,Second>(); return tmp; }
                                              ^^^^^^^^^
    

    我遇到的与此错误相关的其他答案是代码将类型而不是值作为参数传递给函数的结果。

    在这种情况下,函数不接受参数。让问题变得明显的是改变了代码的形式,产生了更好的错误:

    template <uint First, uint Second, typename T>
    struct Thing {
      std::shared_ptr<T> asdf;
      uint get() const { auto tmp = this->asdf->get_value<First,Second>(); return tmp; }
    

    。。。将错误更改为:

    error: declaration of 'Second' shadows template parameter
      uint get() const { auto tmp = this->asdf->get_value<First,Second>(); return tmp; }
    
    error: declaration of 'Second' with type 'auto' requires an initializer
      uint get() const { auto tmp = this->asdf->get_value<First,Second>(); return tmp; }
                                                                ^
    error: expected ';' at end of declaration    };
      uint get() const { auto tmp = this->asdf->get_value<First,Second>(); return tmp; }
                                                                      ^