使用派生类进行c ++模板转换

yur*_*rec 5 c++ templates solaris derived-class

#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;
}
Run Code Online (Sandbox Code Playgroud)

我不明白为什么这个编译(也许有人可以提供详细的解释?它是否与名称查找相关?

顺便说一句,在Solaris上,SunStudio12它没有编译: 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*>

Jam*_*lis 13

std::pair 有一个构造函数模板:

template<class U, class V> pair(const pair<U, V> &p);
Run Code Online (Sandbox Code Playgroud)

"效果:从参数的相应成员初始化成员,根据需要执行隐式转换." (C++ 03,20.2.2/4)

从派生类指针到基类指针的转换是隐式的.

  • 是的,它产生一个`std :: pair(B*,B*)`.然后使用上面的构造函数构造一个`std :: pair(A*,A*)`. (2认同)