C++ 如何调用模板成员函数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12676190/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 16:30:25  来源:igfitidea点击:

How to call a template member function?

c++templates

提问by ritter

Possible Duplicate:
C++ template member function of template class called from template function

可能的重复:
从模板函数调用的模板类的 C++ 模板成员函数

template<class T1>
class A 
{
public:
    template<class T0>
    void foo() const {}
};

template<class T0,class T1>
void bar( const A<T1>& b )
{
    b.foo<T0>();  // This throws " expected primary-expression before ‘>' token"
}

I can change it to

我可以把它改成

b->A<T1>::template foo<T0>();

which compiles fine. However I can also change it to

编译得很好。但是我也可以将其更改为

b.A<T1>::template foo<T0>();

which compiles fine too. eh?

这也编译得很好。嗯?

How does one correctly call the template member function in the sense of the original code?

如何正确调用原代码意义上的模板成员函数?

回答by ritter

Just found it:

刚发现:

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

根据 C++'03 标准 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.

当成员模板特化的名称出现在后缀表达式之后.->中,或在限定 id 中的嵌套名称说明符之后,并且后缀表达式或限定 id 显式依赖于模板参数 (14.6.2 ),成员模板名称必须以关键字 为前缀template。否则,假定该名称命名为非模板。

Correct code is:

正确的代码是:

b.template foo<T0>();

回答by Ninten

you can call the function this way:

你可以这样调用函数:

b.template foo<T0>();