Why do I get an error trying to call a template member function with an explicit type parameter?

流过昼夜 提交于 2020-11-30 02:14:11

问题


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>();
    }
};

回答1:


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!



来源:https://stackoverflow.com/questions/4942703/why-do-i-get-an-error-trying-to-call-a-template-member-function-with-an-explicit

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!