xun*_*ang 1 c++ forward perfect-forwarding c++11
请参阅下面的代码段(请注意,s是一个带有char而不是string的数组):
#include <string>
#include <iostream>
#include <utility>
void func(std::string & s, char a) {
std::cout << "here1" << std::endl;
// ...
}
void func(std::string && s, char a) {
std::cout << "here2" << std::endl;
// ...
}
template <class T>
void foo(T && s) {
std::cout << "foo2" << std::endl;
func(s, ':');
//func(std::forward<T>(s), ':');
}
int main(int agrc, char *argv[])
{
//std::string s("a:b:c:d");
char s[8] = "abcdefg";
foo(std::move(s));
std::string s2("abcd")
foo(s2);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
如果我替换func(s, ':')使用std::forward,它没有区别,foo函数将执行完美转发,std::forward在这种情况下.
std::forward在C++ 11中是否存在对"完美转发"的误解?
它有所作为.在你的情况下,func(s, ':')只会调用func引用的重载a std::string.
问题是命名变量和参数本身就是左值,这也是std::forward首先存在的原因.
在您的示例中,foo即使您不使用,也会为第一次调用选择正确的重载std::forward.这只是因为你实际调用foo了一个char[]用于隐式构造临时的参数std::string.
| 归档时间: |
|
| 查看次数: |
139 次 |
| 最近记录: |