Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Template class with template function

Tags:

c++

templates

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 =(

like image 538
freitass Avatar asked Aug 10 '11 17:08

freitass


1 Answers

The compiler already tells you the answer. The class C is a template with one parameter, and the member function f is a template member function, and you have to define it in the same way:

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

If you define the function at the declaration site, you'll implicitly declare it inline; that's about the only difference practically. There may be stylistic considerations, of course, e.g. never to put function definitions inside class definitions.

As you rightly observe, you will still have to provide the definition in the header file, since you will need to instantiate the template whenever you use it, and thus you need access to all the definitions.

like image 51
Kerrek SB Avatar answered Sep 24 '22 15:09

Kerrek SB