Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ template casting with derived classes

#include <vector>

struct A {int a;};
struct B : public A {char b;};

int main()
{
  B b;
  typedef std::pair<A*, A*> MyPair;
  std::vector<MyPair> v;
  v.push_back(std::make_pair(&b, &b)); //compiler error should be here(pair<B*,B*>)
  return 0;
}

I don't understand why this compiles (maybe somebody can kindly provide detailed explanation? Is it something related to name look-up?

Btw, on Solaris, SunStudio12 it doesn't compile: error : formal argument x of type const std::pair<A*, A*> & in call to std::vector<std::pair<A*,A*> >::push_back(const std::pair<A*, A*> & ) is being passed std::pair<B*, B*>

like image 839
yurec Avatar asked Jan 26 '10 03:01

yurec


1 Answers

std::pair has a constructor template:

template<class U, class V> pair(const pair<U, V> &p);

"Effects: Initializes members from the corresponding members of the argument, performing implicit conversions as needed." (C++03, 20.2.2/4)

Conversion from a derived class pointer to a base class pointer is implicit.

like image 74
James McNellis Avatar answered Nov 20 '22 10:11

James McNellis