c++ - 是否可以将 vector<shared_ptr<T>> 传递给 const vector<shared_ptr<const T>>& 参数?

标签 c++ type-conversion constants shared-ptr

假设我们有以下函数:

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/

相关文章:

c - 以下代码有哪些潜在问题?短 foo() { 短 a,b,c; b=10; c = a + b;返回c; }

c# - 为什么 const mytype _var = new mytype() 不起作用?

c++ - 将 const std::vector<char> 转换为 unsigned char*?

c++ - 错误 C2678:二进制 '>>':找不到采用 'std::stringstream 类型的左侧操作数的运算符

c++ - C和C++的区别 : array size is not honored

spring-mvc - Spring 类型转换不生效

c++ - 'const'最后在类的函数声明中的含义?

c++ - C++中栈的链表实现

c++ - 如果我想在执行过程中将其内存减少一半,我可以使用哪种数据结构

mysql - 从 'float' 转换为 'int' ?