Search code examples
c++templates

How do I define a templated function outside the class when the class itself is templated?


I've tried:

template <typename T>
struct Class1
{
    template <typename U>
    int func(U u);
};


template <typename U>
int Class1::func(U u)
{

}

It doesn't work.

I've also tried:

template <typename T>
struct Class1
{
    template <typename U>
    int func();
};


template <typename T, typename U>
int Class1<T>::func(U u)
{

}

But neither work.


Solution

  • As mentioned in the comments, it's usually recommended to implement templated methods inline.

    However - if you insist on separating the declaration from definition, you can do it in the following way:

    template <typename T>
    struct Class1
    {
        template <typename U>
        int func(U u);
    };
    
    template <typename T>
    template <typename U>
    int Class1<T>::func(U u) 
    {
        return 0;
    }
    

    Live demo

    A side note:
    To answer your question in the comment: this is not what is called template template, but rather a simple method template inside a class template.
    Template template parameters are generally parameters of a template, which are themselves templates instead of being of normal types.
    For more info about template template parameters see here and here.