将非常量向量传递给引用<string> const 向量<const string>?
Pass non-const vector<string> to a function that takes a reference to const vector<const string>?
我有一个函数,我希望能够接受const vector<const string>
,但我也希望用户能够通过vector<string>
。我以为我可以让函数参数成为const的引用,这样非const向量仍然可以接受,但事实并非如此。下面是一个例子:
void test(const vector<const string> &v)
{
return;
}
int main( int argc, char *argv[] )
{
vector<string> v;
test(v);
return 0;
}
我收到的错误是:
error C2664: 'test' : cannot convert parameter 1 from 'std::vector<_Ty>' to 'const std::vector<_Ty> &'
为什么这个例子不起作用,你建议我如何使我的函数工作,以便用户可以通过const vector<const string>
和vector<string>
?由于
这篇文章也许能帮到你。然而,你可以用这种(可怕的)方式强制调用
test(*reinterpret_cast<vector<const string>*>(&v));
在某种程度上也说明了为什么不可能进行自动转换。你可以打破容器的规则:
vector<string> v = {"a", "b"};
vector<const string>& vc = v; //not allowed, of course
v[0].clear(); //<-- but also vc[0] is cleared
相关文章:
- 请解释这句话(cout<<1+int((a<b)^((b-a)&1) )<<endl
- 呼叫运营商<<临时
- cppcheck在const std::string[]上引发警告
- 将std::string传递给WriteConsole API
- 如何防止clang格式在流运算符调用之间添加换行符<<
- 为std::string的某个索引赋值
- <<操作员在下面的行中工作
- std中有类似find_last_of的函数,而string中没有
- 使用 std::string () const 函数启动线程或未来
- 使用char类型将decimal转换为string,将string转换为decimal
- 迭代和比较映射<字符串、矢量<string>> c++ 中的值
- 当我们进行一些操作时,应该使用什么'std::string'或'std::stringstream'?
- 将向量解析<string>为字符串
- 'string.assign(string.data(), 5)' 是明确定义的还是 UB?
- 如何更改大小(std::string)
- "string.h"在构建适用于iOS的qt应用程序中找不到消息
- C++:如何将 unix 时间的字符串转换为 *tm?(使用时间错误:"cannot convert 'String' to 'tm*' ")
- std::string 的对象真的可以移动吗?
- 与'operator='不匹配(操作数类型'String'且"void")
- SegFault 同时使用 std::string::operator+= 和函数作为参数