Template copy constructor question

I

Indrawati Yahya

Hi

I am having trouble in defining a templated class' copy constructor.
Here is the simplest code that represent my problem:

template<typename T1>
class Foo
{
public:
Foo(T1 bar = T1()): _bar(bar), _cached(false) {}
template<typename T2>Foo(const Foo<T2>& foo): _bar(T1(foo._bar)),
_cached(false) {}

//other operations...

private:
T1 _bar;
bool _cached;
};

int main()
{
Foo<int> fooInt;
Foo<double> fooDouble(fooInt);
}

The problem is, this code will not compile, since Foo<double> cannot
access Foo<int> private member(_bar). Is there an elegant way to get
around this, other than providing getters/setters for each members to
be copied?

Thanks!
 
R

Rob Williscroft

Indrawati Yahya wrote in
in comp.lang.c++:
Hi

I am having trouble in defining a templated class' copy constructor.

Minor nit this *isn't* a/the "copy constructor" its a converting
constructor, the compiler will still generate the copy constructor
and us it for copying a Foo said:
Here is the simplest code that represent my problem:

template<typename T1>
class Foo
{

template said:
public:
Foo(T1 bar = T1()): _bar(bar), _cached(false) {}
template<typename T2>Foo(const Foo<T2>& foo): _bar(T1(foo._bar)),
_cached(false) {}
};

int main()
{
Foo<int> fooInt;
Foo<double> fooDouble(fooInt);
}

The problem is, this code will not compile, since Foo<double> cannot
access Foo<int> private member(_bar). Is there an elegant way to get
around this, other than providing getters/setters for each members to
be copied?

Use the friend declaration above.

Rob.
 
I

Indrawati Yahya

Rob Williscroft said:
Indrawati Yahya wrote in
in comp.lang.c++:


Minor nit this *isn't* a/the "copy constructor" its a converting
constructor, the compiler will still generate the copy constructor
and us it for copying a Foo< T > to another Foo< T >.

Thanks for pointing that out, as otherwise it may cause a fatal bug
when the actual copy constructor is called.
Use the friend declaration above.

Doh! My VC++6 rejects the code. Comeau's accepted it fine though.
Thanks!
 

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

Forum statistics

Threads
473,756
Messages
2,569,534
Members
45,007
Latest member
OrderFitnessKetoCapsules

Latest Threads

Top