从模板函数调用模板类的模板成员函数

发布于 2024-08-13 23:32:05 字数 555 浏览 13 评论 0原文

这不会编译:

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:18:错误:“)”标记之前应有主表达式

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

hhh.cpp:23:从这里实例化

hhh.cpp:18: 错误:成员的无效使用(您是否忘记了“&”?)

任何人都可以解释这是为什么吗?有办法让它发挥作用吗?

This doesn't compile:

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
}

The compiler (gcc) says:

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

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

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

hhh.cpp:23: instantiated from here

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

妄司 2024-08-20 23:32:05

尝试以下代码:

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

根据 C++'03 标准 14.2/4:

当成员模板特化的名称出现在后缀表达式中的.->之后,或之后qualified-id 中的nested-name-specifier,并且后缀表达式或qualified-id显式依赖于模板参数(14.6.2),成员模板名称必须是以关键字 template 为前缀。否则,该名称将被假定为非模板名称。

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

Try the following code:

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

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

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.

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).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文