我有一个函数,我希望能够接受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