Chronollo
Chronollo

Reputation: 342

Defining a Single Template for a Member Function within a Class Template with Both Templates Used in Member Function

I'm currently learning how templates work in C++. In particular, I'm looking at the single member function templates within class templates. To understand what I mean, code is found below.

// foo.h
template<typename A>
class foo {
    template<typename B>
    void boo(B);
};

// foo.cpp
template<typename A>
void foo<A>::boo(B value) {} // compiler error: 'Unknown' type name B

// or if I try this

template<typename B>
void foo<A>::boo(B value) {} // compiler error: Use of undeclared identifier A

I'm trying to use two typenames, one from the class template, and one from the single file template, for that specific function. But in those two versions above, I get compiler errors. How would I bypass this problem?

Upvotes: 2

Views: 72

Answers (1)

songyuanyao
songyuanyao

Reputation: 173044

Both the two sets of template parameters are required to define the member template.

(emphasis mine)

If the enclosing class declaration is, in turn, a class template, when a member template is defined outside of the class body, it takes two sets of template parameters: one for the enclosing class, and another one for itself:

E.g.

template<typename A>
template<typename B>
void foo<A>::boo(B value) {} 

Upvotes: 4

Related Questions