Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

c++ - Templates: template function not playing well with class's template member function

This is a minimal test case of some code that I actually have. It fails when it tries to evaluate a.getResult<B>():

test.cpp: In function 'void printStuff(const A&)':
test.cpp:6: error: expected primary-expression before '>' token
test.cpp:6: error: expected primary-expression before ')' token

The code is:

#include <iostream>

template< class A, class B>
void printStuff( const A& a)
{
    size_t value = a.getResult<B>();
    std::cout << value << std::endl;
}

struct Firstclass {
    template< class X >
    size_t getResult() const {
        X someInstance;
        return sizeof(someInstance);
    }
};

int main(int, char**) {
    Firstclass foo;

    printStuff<Firstclass, short int>(foo);
    printStuff<Firstclass, double>(foo);

    std::cout << foo.getResult< double >() << std::endl;

    return 0;
}

If I comment out the printStuff function and where it's called, the foo.getResult< double >() call compiles fine and does what is expected.

Any idea what's going on? I've been working with extensively templated code for a while and have never encountered anything like this.

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

When you refer to a template that is a member of dependent type, you have to prepend it with a keyword template. This is how the call to getResult inside printStuff should look

size_t value = a.template getResult<B>();

This is similar to using the keyword typename when referring to nested typenames in a dependent type. For some reason, the bit about typename with nested types is rather well-known, but the similar requirement for template with nested templates is relatively unknown.

Note that the general syntax structure is a bit different though. The typename is always put in front of the full name of the type, while template is inserted in the middle.

Again, this is only necessary when you are accessing a template member of a dependent type, which in the above example would be A in printStuff. When you call foo.getResult<> in main the type of foo is not dependent, so there's no need to include the template keyword.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...