Template class with template function

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 classC<X>’
source.cpp:4: error: candidate is: template<class X> template<class Y> void C::f(Y)

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

Note: I saw this question , but it seems that the only part that interests me was left separately = (

+5
source share
3 answers

. C - , - f - - , :

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

, inline; . , , . .

, , , , , , .

+13

, :

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

template<class X, class Y>

+1

As an aside, it is preferable to use the keyword "typename" instead of "class" inside the list of template arguments.

-1
source

All Articles