调用模板成员函数无法编译 [英] Call to template member function failing to compile

查看:93
本文介绍了调用模板成员函数无法编译的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对以下形式的代码有一个问题:

I have a problem with a piece of code of the following form:

template<class Type>
class Class1 {
public:
    template<class TypeName1> TypeName1* method1() const {return 0;}
};

struct Type1{};
struct Type2{};

class Class2 {
public:
   template<typename TypeName1, typename TypeName2>
   int method2() {
       Class1<TypeName2> c;
       c.method1<TypeName1>();
       return 0;
   }

   int method1() {
       return method2<Type1, Type2>();
   }
};

int
main() {
   Class2 c;
   return c.method1();
}

在编译器在键盘上编译时:

When compiled with compiler at codepad:

http://codepad.org/ZR1Std4k

我得到以下错误:


t.cpp:在成员函数'int Class2 :: method2()':行15:
在'>'标记编译终止之前的预期主表达式
由于-Wfatal错误。

t.cpp: In member function 'int Class2::method2()': Line 15: error: expected primary-expression before '>' token compilation terminated due to -Wfatal-errors.

冒犯行是模板成员函数的调用:

The offending line is the invocation of the template member function:

c.method1<TypeName1>();


推荐答案

您应该使用 关键字当你调用一个成员函数模板并且你有一个依赖的名字,或 method1 将被解析为 c < 作为小于符号:

You should use the template keyword when you are invoking a member function template and you have a dependent name, or method1 will be parsed as a member variable of c and < as a "less than" symbol:

c.template method1<TypeName1>();

正如@DrewDormann正确指出的,模板关键字是对于所提供的特定类型参数存在 Class1 类模板的特殊化,其中 method1 定义为成员变量而不是函数模板。因此,必须明确指示编译器将 method1 解析为函数模板的名称(如果不是这样)。

As @DrewDormann correctly points out, the reason why the template keyword is required is that a specialization of the Class1 class template could exist for the particular type argument provided, where method1 is defined as a member variable rather than a function template. Thus, the compiler must be explicitly instructed to parse method1 as the name of a function template if this is not the case.

这篇关于调用模板成员函数无法编译的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆