Template functions & class templates syntax

F

Frank Schmitt

Hi!

Suppose I have a class template Foo
with a member function template bar - so far so good:

template <typename T>
struct Foo {
template <typename U>
void bar(const U& u);
};

No problem so far. Now, I want to define bar. This doesn't work:

template <typename T, typename U>
void Foo<T>::bar(const U& u) {
}

It cost me half an hour of trial-and-error to find out
that this does work:

template <typename T> template <typename U>
void Foo<T>::bar(const U& u) {
}

I thought U was just an additional template parameter,
but it seems like two nested template declarations are needed -
why ?

thanks in advance & kind regards
frank
 
R

Rolf Magnus

Frank said:
Hi!

Suppose I have a class template Foo
with a member function template bar - so far so good:

template <typename T>
struct Foo {
template <typename U>
void bar(const U& u);
};

No problem so far. Now, I want to define bar. This doesn't work:

template <typename T, typename U>
void Foo<T>::bar(const U& u) {
}

It cost me half an hour of trial-and-error to find out
that this does work:

template <typename T> template <typename U>
void Foo<T>::bar(const U& u) {
}

I thought U was just an additional template parameter,
but it seems like two nested template declarations are needed -
why ?

Because that's what it is. A nested template. Not a single template with
two parameters.
 
G

Gianni Mariani

Frank said:
Hi!

Suppose I have a class template Foo
with a member function template bar - so far so good:

template <typename T>
struct Foo {
template <typename U>
void bar(const U& u);
};

No problem so far. Now, I want to define bar. This doesn't work:

template <typename T, typename U>
void Foo<T>::bar(const U& u) {
}

It cost me half an hour of trial-and-error to find out
that this does work:

template <typename T> template <typename U>
void Foo<T>::bar(const U& u) {
}

I thought U was just an additional template parameter,
but it seems like two nested template declarations are needed -
why ?

Because !

The correct answer is that it just "IS" that way.

However if you're looking for philosophy, I can imagine that the
creators of the standard nested templates and decided that the best way
to represent these in the second form was to show the nesting. I can
also imagine there would be ambiguity in the syntax if alternatives were
used.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top