为什么尝试调用具有显式类型参数的模板成员函数时出现错误? [英] Why do I get an error trying to call a template member function with an explicit type parameter?
问题描述
我不明白,在我看来, f
的调用是完全明确的,但它无法编译预期的主-expression before'int'
。如果我在调用 f
时注释掉它,它会编译得很好。
template< typename T>
struct A {
template< typename S>
void f(){}
};
template< typename T>
struct B:A< T> {
void g(){
this-> f< int>();
}
};
这是由于一个真正晦涩的标准其中如果你有一个模板试图访问一个模板函数的类型取决于模板参数的对象,你必须以奇怪的方式使用模板
关键字:
this-> template f< int>();
这与类似于 typename
它出现了依赖类型,除了应用于函数。特别是,如果你省略了模板
关键字,在
this-> f< int>()
/ p>
((this-> f)< int) ()
这没有意义使用关键字 template
在这里消除了歧义,并强制编译器认识到它正在查看一个完全有效的调用模板成员函数,而不是乱码大量的符号。 p>
希望这有助于!
I don't get it, it seems to me that the call to f
is completely unambiguous, but it fails to compile with expected primary-expression before ‘int’
. If I comment out the line with the call to f
, it compiles fine.
template<typename T>
struct A {
template<typename S>
void f() { }
};
template<typename T>
struct B : A<T> {
void g() {
this->f<int>();
}
};
This is due to a really obscure provision of the standard in which if you have a template that tries to access a template function in an object whose type depends on a template argument, you have to use the template
keyword in a weird way:
this->template f<int>();
This is similar to the weirdness with typename
that comes up with dependent types, except as applied to functions. In particular, if you leave out the template
keyword, there's a parsing ambiguity between
this->f<int>()
(what you intended), and
((this->f) < int) > ()
which makes no sense (hence your error). The use of the keyword template
here disambiguates and forces the compiler to recognize that it's looking at a perfectly valid call to a templated member function rather than a garbled mass of symbols.
Hope this helps!
这篇关于为什么尝试调用具有显式类型参数的模板成员函数时出现错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!