假设我们有以下函数:
void doStuff(const std::vector<std::shared_ptr<const Foo>>& fs) { }
有没有办法(安全地)传递 std::vector<std::shared_ptr<Foo>>
到这个参数?例如:
std::vector<std::shared_ptr<Foo>> foos;
doStuff(foos);
这种隐式转换失败了,但是可以通过强制转换安全地完成吗? (这在理论上似乎是安全的,因为 doStuff
函数将无法修改 vector ,也无法修改其中的对象。)
最佳答案
简短的回答是“否”。
给定一个类模板
template <typename T> struct Foo {};
Foo<int>
和 Foo<const int>
是两种不同的类型。两种类型之间没有隐式转换。
我的建议是制作 doStuff
一个函数模板。
template <typename T>
void doStuff(const std::vector<T>& fs) { }
或
template <typename T>
void doStuff(const std::vector<std::shared_ptr<T>>& fs) { }
如果您没有修改 doStuff
的选项, 复制 doStuff
中的代码对于 shared_ptr<Foo>
可能是唯一明智的做法。
关于c++ - 是否可以将 vector<shared_ptr<T>> 传递给 const vector<shared_ptr<const T>>& 参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42493116/