155

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 can I do this? What is the correct syntax?

digito_evo
  • 3,216
  • 2
  • 14
  • 42
Michael
  • 2,356
  • 3
  • 21
  • 24
  • Why not just do the function decl inside the class decl (see http://codepad.org/wxaZOMYW)? You can't move the function decl out of the header anyway, so... – hiobs Dec 27 '11 at 07:33
  • @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 Aug 01 '13 at 00:31
  • 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 Jan 09 '19 at 17:22

1 Answers1

233

Write this:

template <class T>
template <class U>
void MyClass<T>::foo() { /* ... */ }
Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084