template compilation problem

M

Mark P

I'm having a problem compiling some template code. Here's a seemingly
useless block of code which I've stripped down to illustrate my problem.
Why is the second call to a.foo not accepted by the compiler? Advice
and suggestions are welcomed.

Thanks,
Mark

#include <iterator>
#include <list>

using namespace std;

template <typename T>
struct A
{
template <typename OutIter>
void foo (OutIter& oi);
};


template <typename T>
template <typename OutIter>
void A<T>::foo (OutIter& oi)
{}

int main ()
{
A<int> a;
list<int> output;

// this is fine:
back_insert_iterator<list<int> > bii = back_inserter(output);
a.foo(bii);

// this is not:
a.foo(back_inserter(output));
}
 
P

Pete C

template said:
struct A
{
template <typename OutIter>
void foo (OutIter& oi);
};
<snip>
a.foo(back_inserter(output));

The error has nothing to do with templates. The problem is that you
can't bind a temporary to a non-const reference (as I imagine your
compiler is telling you).
For example:
int &a = int(5);
is not valid, but
const int &a = int(5);
is OK. Your argument to foo is a non-const reference. Either pass it by
value, or do what you have done above.
 
M

Mark P

Mark said:
I'm having a problem compiling some template code. Here's a seemingly
useless block of code which I've stripped down to illustrate my problem.
Why is the second call to a.foo not accepted by the compiler? Advice
and suggestions are welcomed.

Hmm, I think I've figured this one out. The compiler doesn't like my
passing a temporary by non-constant reference. As you might guess, the
argument here is an Output Iterator and it suits me fine to modify and
discard the temporary, but I guess rules are rules.

Thanks,
Mark
 
D

Diego Martins

Pete said:
The error has nothing to do with templates. The problem is that you
can't bind a temporary to a non-const reference (as I imagine your
compiler is telling you).
For example:
int &a = int(5);
is not valid, but
const int &a = int(5);
is OK. Your argument to foo is a non-const reference. Either pass it by
value, or do what you have done above.

is this related to the proposed C++ extension && on arguments?
 

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
474,431
Messages
2,571,677
Members
48,796
Latest member
Greg L.

Latest Threads

Top