A problem with conversation in template

M

miaohua1982

the code is as follows:

#include<iostream>
using namespace std;

template<class T>
class Myauto_ptr
{
public:
Myauto_ptr(T*ptr=0):_Myptr(ptr){}
~Myauto_ptr(){ delete _Myptr;}

template<class another_T>
operator Myauto_ptr<another_T>(){ return
Myauto_ptr<another_T>(_Myptr);}

T& operator*(){ return *_Myptr;}
T* operator->(){ return _Myptr;}
private:
T * _Myptr;
};
class base
{
public:
void print(){cout<<"I am base!"<<endl;}
};
class Tuple:private base{};


void Test( const Myauto_ptr<base> &pmp, int num)
{
cout<<"in Test"<<endl;
}

int main()
{
Myauto_ptr<Tuple> pt1(new Tuple);
Test( pt1, 10); //Myauto_ptr<Tuple> converts to
Myauto_ptr<base> ,but Tuple private inherits from base ,why such
conversation is successful(in VC)

Tuple * ptrT = new Tuple;
base * ptrB = ptrT; //it's compiler error, but why "Test( pt1,
10)" is successful?
return 0;
}


I just compile the code in VC7&&VC8. well, in gcc, Test( pt1, 10)
results in a compile error. So, it's a VC's bug? Or ,the gcc is wrong?
Or both are OK. Is there someone can tell me why?
 
G

Gianni Mariani

I just compile the code in VC7&&VC8. well, in gcc, Test( pt1, 10)
results in a compile error. So, it's a VC's bug? Or ,the gcc is wrong?
Or both are OK. Is there someone can tell me why?

gcc 4.1.1 is correct.
VC8 is wrong.
comeau 4.3.8 is correct.

Basically, the conversion operator template "Myauto_ptr" is accessing
base via private inheritance which it is not allowed to do.

As an aside, you'll want to avoid the conversion operator for smart
pointers. They get in the way with ambiguous conversions, the best way
is to overload the constructor.
 

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,769
Messages
2,569,582
Members
45,069
Latest member
SimplyleanKetoReviews

Latest Threads

Top