有没有办法在不污染命名空间的情况下使用 boost::assign 运算符?

发布于 2024-10-15 23:17:04 字数 301 浏览 2 评论 0原文

我尝试避免在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

记忆で 2024-10-22 23:17:04

您的假设是错误的,它会污染命名空间:using namespace 功能正是为这种用途而创建的。

它只会“污染”声明 using namespace 的作用域,在这种情况下,好处(使用运算符)远远大于缺点(这种“污染”可以忽略不计)范围的大小)。

例如,您可以:

void foo()
{
   // no symbol of boost::assign is polluting here

   std::vector tmp;

   {
      using namespace boost::assign ;
      // brings in this scope all the symbols of boost::assign
      tmp += "abc","def","asdf","foo","blah","dfkef";
   }

   // no symbol of boost::assign is polluting here
}

您应该在 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:

void foo()
{
   // no symbol of boost::assign is polluting here

   std::vector tmp;

   {
      using namespace boost::assign ;
      // brings in this scope all the symbols of boost::assign
      tmp += "abc","def","asdf","foo","blah","dfkef";
   }

   // no symbol of boost::assign is polluting here
}

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文