kar*_*doc 5 c++ rvalue-reference c++11
我想重载一个函数,以便它以某种方式操作它的参数,然后返回对参数的引用 - 但如果参数不可变,那么它应该返回参数的操纵副本.经过多年的讨论,这就是我想出来的.
using namespace std;
string& foo(string &in)
{
in.insert(0, "hello ");
return in;
}
string foo(string &&in)
{
return move(foo(in));
}
string foo(const string& in)
{
return foo(string(in));
}
Run Code Online (Sandbox Code Playgroud)
这段代码似乎工作正常,但我很想知道是否有人能想到更好的方法来做到这一点.
这是一个测试程序:
int main(void)
{
string var = "world";
const string var2 = "const world";
cout << foo(var) << endl;
cout << var << endl;
cout << foo(var2) << endl;
cout << var2 << endl;
cout << foo(var + " and " + var2) << endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
正确的输出是
hello world
hello world
hello const world
const world
hello hello world and const world
Run Code Online (Sandbox Code Playgroud)
如果我能做到这一点,我认为它会稍微整洁一点:
string& foo(string &in)
{
in.insert(0, "hello ");
return in;
}
string foo(string in)
{
return move(foo(in));
}
Run Code Online (Sandbox Code Playgroud)
当然,这不起作用,因为大多数函数调用foo都是模棱两可的 - 包括调用foo本身!但如果我能以某种方式告诉编译器优先考虑第一个......
正如我所说,我发布的代码工作正常.我不喜欢的主要是重复的额外代码.如果我有一堆这样的功能会变得非常混乱,而且大部分会非常重复.所以作为我问题的第二部分:有人能想到一种方法来自动生成第二和第三个foo函数的代码吗?例如
// implementation of magic_function_overload_generator
// ???
string& foo(string &in);
magic_function_overload_generator<foo>;
string& bar(string &in);
magic_function_overload_generator<bar>;
// etc
Run Code Online (Sandbox Code Playgroud)
我会一起摆脱所有引用,只需编写一个传递并按值返回的函数:
std::string foo(std::string in)
{
in.insert(0, "hello ");
return in;
}
Run Code Online (Sandbox Code Playgroud)
如果传递左值,则将复制输入字符串.如果你传递右值,它将被移动.
离开函数时,命名返回值优化可能会启动,因此返回基本上是无操作.如果编译器决定不这样做,结果将被移动(即使in是左值).
关于rvalue引用的好处是你必须少考虑在用户代码中放置引用的位置以提高效率.对于可移动类型,按值传递实际上是有效的.
| 归档时间: |
|
| 查看次数: |
2149 次 |
| 最近记录: |