【发布时间】:2018-05-24 22:53:47
【问题描述】:
我无法理解为什么我的代码无法在此处编译。我从标准库中收到了很多错误消息,类似于
main3.cpp:10:20: required from ‘void addAndCout(T&&) [with T = const char (&)[11]]’
main3.cpp:20:28: required from here
/usr/include/c++/5/bits/alloc_traits.h:450:27: error: forming pointer to reference type ‘const char (&)[11]’
using pointer = _Tp*;
^
/usr/include/c++/5/bits/alloc_traits.h:453:39: error: forming pointer to reference type ‘const char (&)[11]’
using const_pointer = const _Tp*;
这对我来说没有意义,因为我认为 T&& 在没有推导 T 时是一个通用引用,它应该能够绑定到右值或左值。发布的这个示例是我试图从 Scott Meyer 的“Effective Modern C++”中复制一个部分,其中我正在阅读有关通用引用的内容。 Photo of example from the book
我只是想知道为什么这不会编译或者我在这里缺少什么,因为据我所知它实际上与示例相同。
#include <iostream>
#include <vector>
#include <string>
using std::cout;
using std::endl;
template<typename T>
void addAndCout(T &&name)
{
std::vector<T> v;
cout << name << endl;
v.emplace_back(std::forward<T>(name));
}
int main(int argc, char **argv)
{
std::string name {"test"};
addAndCout(std::string("rvalue")); // FINE move rvalue instead of copying it
addAndCout("New string"); // ERROR make a new string instead of copying
addAndCout(name); // ERROR copy lvalue
}
【问题讨论】:
-
您能解释一下局部向量的用途吗?当函数返回时它会被销毁,因此无论如何在其中存储值都是多余的。
标签: c++ c++14 forwarding-reference