Alex Rivera | Logout

Template class with template function

Asked 2011-08-10T17:34:46.167
10

Can anyone tell what is wrong with this piece of code?

template<class X>
class C {
public:
    template<class Y> void f(Y); // line 4
};

template<class X, class Y>
void C<X>::f(Y y) { // line 8
    // Something.
}

int main() {
    C<int> c;
    char a = 'a';
    c.f(a);
    return 0;
}

Compilation:

$ g++ source.cpp 
source.cpp:8: error: prototype for ‘void C<X>::f(Y)’ does not match any in class ‘C<X>’
source.cpp:4: error: candidate is: template<class X> template<class Y> void C::f(Y)

I now that I can accomplish the task by declaring and defining the function at line 4, but what would be the consequences of declaring and defining the function at the same time compared to doing it separately? (This is not a discussion about declaring a function at header vs source file)

Note: I have seen this question but is seems that the only part that interests me was left apart =(

Edit
Report

1 Answer

3

The error tells you exactly, your code should look like this:

template<class X>
class C {
public:
    template<class Y> void f(Y); // line 4
};

template<class X> template<class Y>
void C<X>::f(Y y) { // line 8
    // Something.
}

int main() {
    C<int> c;
    char a = 'a';
    c.f(a);
    return 0;
}

Your class is not defined as template<class X, class Y>

answered 2011-08-10T17:39:11.417

Your Answer