ChatGPT解决这个技术问题 Extra ChatGPT

Template function inside template class

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?

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: 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.
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.

K
Kerrek SB

Write this:

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

void MyClass::foo()... thanks, I tried it before, but it doesn't work to me.. perhaps I had to do clean project.
@user1074367: No, I think it's as I say.
actually I wrote: template template void MyClass::foo() { U a; a.invoke(); } and it works
@user1074367: Err... yes, that's what I say in the answer, non?
@mike: Member templates are a perfectly normal and common thing.