有没有办法在不污染命名空间的情况下使用 boost::assign 运算符?
我尝试避免在 C++ 中“使用命名空间”,以避免污染我的命名空间。但是,我想利用 boost 赋值运算符来做这样的事情:
std::vector tmp; tmp += "abc","def","asdf","foo","blah","dfkef";
不添加“using namespace boost::assign;”这会产生一个错误:
error: no match for 'operator+=' in 'tmp += "abc"'
有没有办法在 boost 中使用这些运算符而不使用名称空间?
I try to avoid "using namespace" in my C++ to avoid polluting my namespace. However, I would like to make use of boost assignment operators to do things like this:
std::vector tmp; tmp += "abc","def","asdf","foo","blah","dfkef";
Without adding "using namespace boost::assign;" this produces an error:
error: no match for 'operator+=' in 'tmp += "abc"'
Is there a way to make use of these operators in boost without using the namespace?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的假设是错误的,它会污染命名空间:
using namespace
功能正是为这种用途而创建的。它只会“污染”声明
using namespace
的作用域,在这种情况下,好处(使用运算符)远远大于缺点(这种“污染”可以忽略不计)范围的大小)。例如,您可以:
您应该在
using namespace
带来的语法糖和它可能带来的潜在污染之间做出平衡。一个好的折衷方案可能是将其限制为函数体,或者,如果您像我一样偏执,则仅为此
using
语句创建一个范围...作为一个有趣的旁注,最糟糕的情况是解决方案是将 using 放在带有导出符号的公共标头中。
You're wrong in your assumption it will pollute the namespace: the
using namespace
feature was exactly created for this kind of uses.It will only "pollute" the scope where the
using namespace
is declared, and in this case, the benefits (using the operators) is by far greater than the drawbacks (this "pollution" is as negligible as the size of the scope).For example, you could have:
You should decide a balance between the syntactic sugar brought by the
using namespace
and the potential pollution it could bring over.A good compromise could be to limit it to a function body, or, if you are as paranoid as I am, create a scope just for this
using
statement...As an amusing side note, the worst solution would be to put the using in a public header with exported symbols.