135
votes

I have this code:

template <class T>
class MyClass {
    public:
        template <class U>
        void foo() {
            U a;
            a.invoke();
        }
};

I want it in this form:

template <class T>
class MyClass {
    public:
        template <class U>
        void foo();
};

template <class T> /* ????? */
void MyClass<T>::foo() {
    U a;
    a.invoke();
}

How I can to do this? What is the right syntax?

1
Why not just do the function decl inside the class decl (see codepad.org/wxaZOMYW)? You can't move the function decl out of the header anyway, so... - hiobs
@hiobs: FWIW, you can move the declaration into a CPP file. That said, I've only done this once to do some hackery. In that case, knowing how to do this is essential. - Thomas Eding
Sometimes one must move the function definition outside of the class, after definition of dependencies needed by the function body. This happens when class A uses class B and B also uses A. In that case you declare A and B, then define A and B methods. - Wheezil

1 Answers

201
votes

Write this:

template <class T>
template <class U>
void MyClass<T>::foo() { /* ... */ }