Template function inside template class
Asked Answered
S

1

161

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?

Schear answered 27/12, 2011 at 1:27 Comment(3)
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...Breathtaking
@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.Romilly
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.Swept
E
240

Write this:

template <class T>
template <class U>
void MyClass<T>::foo() { /* ... */ }
Ecumenical answered 27/12, 2011 at 1:31 Comment(8)
void MyClass<T>::foo<T>()... thanks, I tried it before, but it doesn't work to me.. perhaps I had to do clean project.Schear
@user1074367: No, I think it's as I say.Ecumenical
actually I wrote: template <class T> template <class U> void MyClass<T>::foo() { U a; a.invoke(); } and it worksSchear
@user1074367: Err... yes, that's what I say in the answer, non?Ecumenical
sorry, you are right, my mistake... I thought, you wrote MyClass<U>Schear
@user1074367: I'm not saying foo<U>... hit the refresh button, maybe you're seeing an earlier edit :-)Ecumenical
I know this is old, but I can't find much more info on it... Is this a typical design that appears often or maybe hints at a bad design?Dang
@mike: Member templates are a perfectly normal and common thing.Ecumenical

© 2022 - 2024 — McMap. All rights reserved.