<<具有多个参数的运算符 [英] << operator with multiple parameters

查看:92
本文介绍了<<具有多个参数的运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只想知道是否可以为重载运算符<<

I just want to know if we can give two or more parameters to an overload of operator <<

一个例子将更加明确:

anyType         operator<<(arg p1, arg p2)
{
DoSomethingWith(p1);
DoSomethingWith(p2);
return (*this);
}

并像这样使用它:

anyVar << anyVar2, anyVar3;

推荐答案

否,这是不可能的.

您能找到的最接近的是:

The closest you can come would be something like:

anyType         operator<<(std::pair<arg, arg> p)
{
  DoSomethingWith(p.first);
  DoSomethingWith(p.second);
  return (*this);
}

anyvar << std::make_pair(a1, a2);

或者,通过使anyType::operator<<(arg)返回一个仅保留其参数的临时对象并实现一个实际起作用的tempObject::operator<<(arg),您可以做一些更复杂的事情来有效控制对操作员的调用.然后可以将其称为anyvar << arg1 << arg2.除了成为学习经历之外,我真的怀疑是否值得为此烦恼.

Alternatively, you could do something much more complicated to effectively curry the call to your operator, by having anyType::operator<<(arg) return a temporary object which just holds on to its argument and implements a different tempObject::operator<<(arg) which actually does the work. You can then call that as anyvar << arg1 << arg2. I really doubt whether it is worth the trouble, aside from being a learning experience.

类似于这种样式的东西通常用在构建器"模式中,但是使用成员函数而不是显式运算符.这很有用,因为您可以安排有效地使配置参数与订单无关.

Something similar to that style is often used in the "builder" pattern, but using member functions rather than an explicit operator. That's useful because you can arrange to effectively make configuration arguments order-independent.

这篇关于&lt;&lt;具有多个参数的运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆