prefer conversion operator over conversion constructor

Viewed 2006

I have the following code snippet:

class A
{
public:
  A() : x_(0), y_(0) {}

  A(int x, int y) : x_(x), y_(y) {}

  template<class T>
  A(const T &rhs) : x_(rhs.x_), y_(rhs.y_)
  {
  }

  int x_, y_;
};

class B
{
public:
  B() {}

  operator A() const { return A(c[0],c[1]); }
  int c[2];
};

void f()
{
  B b;
  (A)b; // << here the error appears, compiler tries to use 
        //         template<class T> A(const T &rhs)
}

Why compiler uses A's constructor? How can I make it use B's conversion operator to A?

I use MSVS2010 compiler. It gives me these errors:

main.cpp(9): error C2039: 'x_' : is not a member of 'B'
          main.cpp(17) : see declaration of 'B'
          main.cpp(28) : see reference to function template instantiation 'A::A<B>(const T &)' being compiled
          with
          [
              T=B
          ]
main.cpp(9): error C2039: 'y_' : is not a member of 'B'
          main.cpp(17) : see declaration of 'B'

UPD: All right, implicit convert as Nawaz said really works. Let's make it more complicated, how make the following code work?

void f()
{
  std::vector<B> b_vector(4);
  std::vector<A> a_vector( b_vector.begin(), b_vector.end() );
}

UPD: A is the class in 3rd party lib which code I can't edit, so I can't remove A's converting constructor.

UPD: the simplest solution I've found for the moment is to define specialization of converting constructor for B. It can be done outside of 3rd party lib:

template<> A::A( const B &rhs ) : x_(rhs.c[0]), y_(rhs.c[1]) {}
6 Answers
Related