【问题标题】:function overloading with a lot of arguments带有很多参数的函数重载
【发布时间】:2012-09-23 19:57:51
【问题描述】:

假设我在 C++ 中有这个构造函数:

 A::A( std::string const& name,
       std::string const& type,
       std::vector<B> const& b_vec,
       bool unique )
     : _name(name), _type(type), _b_vec(b_vec), _unique(unique)
     { };

我想在参数是右值的情况下重载这个构造函数(我想在那里使用移动语义)。

 A::A( std::string && name,
       std::string && type,
       std::vector<B> && b_vec,
       bool unique )
     : _name(name), _type(type), _b_vec(b_vec), _unique(unique)
     { };

当所有参数都是右值时,上面的方法可以正常工作,但假设只有其中一些是在下一个示例中:

 // create some lvalues somehow
 std::string name   = "stack overflow";
 std::vector<B> vec = { ... }; // implementation of B's constructot is not important

 // call a mixed constructor
 A new_A_instance(name, "cool-website", vec, true);

据我了解,由于 'const&' 不能绑定到 '&&' 但 '&&' 可以绑定到 'const&' 将使用第一个(非移动)构造函数。

这似乎不是最理想的,因为四个参数中的两个可以移动(因为它们是右值)而不是被复制(如第一个构造函数中的情况)。

所以我可以为这种特定情况重载运算符,但可以轻松地想象其他参数是右值而其他参数是左值的情况。我应该为每种情况重载构造函数吗?随着参数数量的增加,这将组合导致非常多的重载......

我有点感觉有更好的解决方案(也许使用模板,但我的模板知识低得可耻)。

注意:这个问题与重载传递引用函数以移动函数本身无关,但我发现这是一个很好的例子(特别是因为重载并没有感觉不同的)。另请注意,我只是以构造函数为例,但重载的函数可以是任何东西。

【问题讨论】:

  • 右值 bool 和 const bool 完全没有意义。
  • @Kerrek:我同意。不知道为什么我把它们放在那里。

标签: c++ overloading


【解决方案1】:

按值传递,这就是移动语义的用途:

 A::A(std::string name, std::string type, std::vector<B> b_vec, bool unique )
   : _name(std::move(name)), _type(std::move(type)), _b_vec(std::move(b_vec)),
     _unique(unique)
 { };

这在每种情况下都有预期的行为。按值传递临时值允许编译器执行复制省略,它几乎总是这样做。

请注意,在您的第二个代码中,由于您不使用std::move,因此会制作副本。写的时候请注意

void foo(bar&& x)
{
    ...
}

那么在foo 的主体中,x 是一个左值。具有名称的对象总是左值。在这个正文中,如果您打算将x 作为右值传递,则必须使用std::move(x)

【讨论】:

  • 其实编辑不太正确。 x 确实总是 bar&amp;&amp;。但这不是右值!请注意,bar&amp;&amp; 表示“rvalue reference”,而不是“rvalue”。
  • 所以这段代码会胜过 pass-by-ref 代码,同时仍然保持传递对象的常量性?
  • @romeovs:是的。尽可能按值传递。
  • @AlexandreC.:我知道你的意图,但它根本不正确。这并不比声称 int 引用与 int 相同。这不是... :-( 换句话说,右值引用可以绑定到右值,但它本身不是右值。它只是一个引用。
  • @romeovs:事实上它一直存在。例如,请参阅cpp-next.com/archive/2009/08/want-speed-pass-by-value
猜你喜欢
  • 2011-04-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-17
  • 2012-04-10
相关资源
最近更新 更多