将vector <shared_ptr <Foo >>>隐式转换为vector <shared_ptr <const Foo >>

Ala*_*ing 4 c++ casting vector shared-ptr implicit-conversion

根据此页面,您可以隐式转换shared_ptr<Foo>shared_ptr<const Foo>.这很有道理.

但是,我碰到一个错误,当我尝试将转换std::vector包含shared_ptr<Foo>一个包含shared_ptr<const Foo>.

有没有一种很好的方法来实现这种转换?

Jam*_*lis 9

否: std::vector<shared_ptr<Foo> >并且std::vector<shared_ptr<const Foo> >是不同的类型,因此您不能将一个对象视为另一个类型的对象.

如果你真的需要a std::vector<shared_ptr<const Foo> >,你可以轻松地创建一个与shared_ptr原始元素相同的元素:

std::vector<shared_ptr<Foo> > v;
std::vector<shared_ptr<const Foo> > cv(v.begin(), v.end());
Run Code Online (Sandbox Code Playgroud)

但是,如果您根据迭代器编写代码,则不应该有任何问题.也就是说,而不是使用

void f(const std::vector<shared_ptr<const Foo> >&);

// used as:
std::vector<shared_ptr<const Foo> > v;
f(v);
Run Code Online (Sandbox Code Playgroud)

你应该使用

template <typename ForwardIterator>
void f(ForwardIterator first, ForwardIterator last);

// used as:
std::vector<shared_ptr<const Foo> > v;
f(v.begin(), v.end());
Run Code Online (Sandbox Code Playgroud)

这样,函数f只需要它获得一系列可用作指针的东西const Foo(或者shared_ptr<const Foo>,如果函数假定范围包含shared_ptrs).

当一个函数占用一个范围而不是一个容器时,你将该函数与底层数据分离:它不再重要的是数据实际是什么或它是如何存储的,只要你能以你需要使用它的方式使用它它.

  • 使用迭代器可能很有用,但是将函数作为模板是一个非常糟糕的解决方案,除非许多不同类型真正需要该函数. (2认同)