Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
153 views
in Technique[技术] by (71.8m points)

c++ - Calling template function within template class

Disclaimer: The following question probably is so easy that I might be shocked seeing the first answer. Furthermore, I want to apologize for any duplicate questions - syntactic problems are not always easy to identify be verbal explanation and thus searching for them is not as easy...

But enough of that. I have a two templated classes, one of those has a templated member function, the other class attempts to call that function. A minimal, error producing example is shown below:

#include <iostream>

template <typename T>
class Foo {
public:
    Foo() {
    }

    template <typename outtype>
    inline outtype bar(int i, int j, int k = 1) {
        return k;
    }

};

template <typename T>
class Wrapper {
public:
    Wrapper() {
    }

    double returnValue() {
        Foo<T> obj;
        return obj.bar<double>(1,2); // This line is faulty.
    }

};

int main() {
    Wrapper<char> wr;
    double test = wr.returnValue();
    std::cout << test << std::endl;
    return 0;
}

At compile time, this results in

expected primary-expression before 'double'
expected ';' before 'double'
expected unqualified-id before '>' token

where all error messages are directed at the linke marked in the code.

I allready thank you for your ideas, no matter how obvious they are.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
obj.bar<double>(1,2); // This line is faulty.

The template keyword is required here, as obj is an instance of a type Foo<T> which depends on the template parameter T, and so the above should be written as:

obj.template bar<double>(1,2); //This line is corrected :-)

Read @Johannes's answer here for detail explanation:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...