C ++模板铸造用派生类
-
22-09-2019 - |
题
#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;
}
我不明白为什么这个编译(也许有人可以请提供详细的解释?有什么事情涉及到名称查找?
顺便说一下,在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*>
解决方案
std::pair
有一个构造模板:
template<class U, class V> pair(const pair<U, V> &p);
“效果:从参数的对应的成员初始化部件,根据需要执行隐式转换。” (C ++ 03,20.2.2 / 4)
转换从派生类指针指向一个基类指针是隐式的。
其他提示
由于B从A衍生,向量v将包含指向到对象B的基类结构。因此,可以访问A的成员,即
std::cout << v[0].first->a;
编辑: 我的错误,如下面指出的,仍可以转换为B型的指针,因为该载体是指针,而不是对象,所以没有发生对象切片。
一个调用诸如
std::cout << v[0].first->b;
不会编译由于在矢量的元素是基类指针和不具有铸造不能指向派生类的成员,即
std::cout << static_cast<B*>(v[0].first)->b;
另外请注意,动态铸造,如在
std::cout << dynamic_cast<B*>(v[0].first)->b;
不会与GCC以下错误编译:
cast.cpp:14: error: cannot dynamic_cast ‘v.std::vector<_Tp, _Alloc>::operator[] [with _Tp = std::pair<A*, A*>, _Alloc = std::allocator<std::pair<A*, A*> >](0u)->std::pair<A*, A*>::first’ (of type struct A*’) to type struct B*’ (source type is not polymorphic)
不隶属于 StackOverflow