从模板函数调用的模板类的模板成员函数 [英] template member function of template class called from template function

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

问题描述

这无法编译:

template<class X> struct A {
   template<int I> void f() {}
};

template<class T> void g()
{
   A<T> a;
   a.f<3>();  // Compilation fails here (Line 18)
}

int main(int argc, char *argv[])
{
   g<int>();  // Line 23
}

编译器(gcc)说:

hhh.cpp:在函数'void g()':

hhh.cpp: In function 'void g()':

hhh.cpp:18:错误:预期在')'标记之前的主表达式

hhh.cpp:18: error: expected primary-expression before ')' token

hhh.cpp:在函数'void g()[with T = int]'中:

hhh.cpp: In function 'void g() [with T = int]':

hhh.cpp:23:从此处实例化

hhh.cpp:23: instantiated from here

hhh.cpp:18:错误:成员的无效使用(您忘了'&'吗?)

hhh.cpp:18: error: invalid use of member (did you forget the '&' ?)

有人可以解释为什么会这样吗?

Can anyone explain why this is? Is there a way to get it to work?

推荐答案

请尝试以下代码:

template<class T> void g()
{
   A<T> a;
   a.template f<3>();  // add `template` keyword here
}

根据C ++'03 Standard 14.2 / 4:

According to C++'03 Standard 14.2/4:


当成员模板专业化名称出现在之后。或< 后缀表达式中的code>-> 或 qualified-id中嵌套名称说明符之后,并且postfix-expression或qualified-id显式依赖于模板参数(14.6.2),成员模板名称必须以关键字 template 。

When the name of a member template specialization appears after . or -> in a postfix-expression, or after nested-name-specifier in a qualified-id, and the postfix-expression or qualified-id explicitly depends on a template-parameter (14.6.2), the member template name must be prefixed by the keyword template. Otherwise the name is assumed to name a non-template.

根据n2857 14.3草案,未来的C ++标准似乎仍然需要此关键字。 / 4。一些编译器具有特殊的模式,该模式允许无错误地编译原始代码(Comeau以所谓的放松模式进行编译)。

Future C++ Standard seems to be still require this keyword according to draft n2857 14.3/4. Some compilers has special mode that allows to compile original code without errors (Comeau compiles it in so called relaxed mode).

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

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