代码之家  ›  专栏  ›  技术社区  ›  Seth Johnson

模板:模板函数与类的模板成员函数不匹配

  •  22
  • Seth Johnson  · 技术社区  · 15 年前

    这是我实际拥有的一些代码的最小测试用例。当它尝试评估时失败 a.getResult<B>() :

    test.cpp: In function 'void printStuff(const A&)':
    test.cpp:6: error: expected primary-expression before '>' token
    test.cpp:6: error: expected primary-expression before ')' token
    

    代码是:

    #include <iostream>
    
    template< class A, class B>
    void printStuff( const A& a)
    {
        size_t value = a.getResult<B>();
        std::cout << value << std::endl;
    }
    
    struct Firstclass {
        template< class X >
        size_t getResult() const {
            X someInstance;
            return sizeof(someInstance);
        }
    };
    
    int main(int, char**) {
        Firstclass foo;
    
        printStuff<Firstclass, short int>(foo);
        printStuff<Firstclass, double>(foo);
    
        std::cout << foo.getResult< double >() << std::endl;
    
        return 0;
    }
    

    如果我评论 printStuff 函数及其调用位置 foo.getResult< double >() 调用编译良好,并按预期执行。

    知道怎么回事吗?我使用广泛模板化代码已经有一段时间了,从未遇到过类似的情况。

    2 回复  |  直到 15 年前
        1
  •  37
  •   AnT stands with Russia    15 年前

    如果引用的模板是依赖类型的成员,则必须在其前面加上关键字 template . 这就是呼叫的方式 getResult 里面 printStuff 应该看看

    size_t value = a.template getResult<B>();
    

    这类似于使用关键字 typename 引用依赖类型中的嵌套类型名时。出于某种原因 类别名 对于嵌套类型是相当有名的,但是对于 模板 使用嵌套模板是相对未知的。

    注意,一般的语法结构有点不同。这个 类别名 总是放在类型的全名前面,而 模板 插入到中间。

    同样,只有在访问 从属型 ,在上面的示例中, A 在里面 印刷品 . 当你打电话 foo.getResult<> 在里面 main 类型 foo 不依赖,因此不需要包括 模板 关键字。

        2
  •  9
  •   Kirill V. Lyadvinsky    15 年前

    根据C++标准142/4,您的代码格式不正确:

    当成员模板专用化的名称出现在 . -> 在一个 后缀表达式 ,或之后 嵌套名称说明符 在一个 合格身份证 ,并且后缀表达式或限定ID显式依赖于模板参数(14.6.2),成员模板名称必须以关键字作为前缀。 template . 否则,将假定该名称命名非模板。

    所以,你应该写 size_t value = a.template getResult<B>();