1. 使用可变参数模板与 forward 机制来编写函数, 实现将其实参不变地传递给其他函数(保持实参的原始类型)
1.1 eg
class StrVec {public:template <class... Args> void emplace_back (Args&&...);}
模板参数包扩展中的模式是 &&, 意味着每个函数参数将是一个指向其对应实参的右值引用。
template <class... Args> inline void StrVec::emplace_back (Args && args){chk_n_alloc ( ); / / 如果需要的话重新分配 StrVec 内存空间alloc.construct (first_free++, std::forward<Args> (args)...);}
1.2 std::forward (args ) …
扩展了模板参数包 Args扩展了函数参数包std::forward (ti) :
其中Ti表示模板参数包中第i个元素的类型, ti表示函数参数包中第i个元素。
eg.
StrVec svec;//将cccccccccc 添加为新的尾元素//construct 调用中的模式会扩展出 std::forward<int> (10) , std::forward<char> (c)svec.emplace_back (10, 'c' );
如果用一个右值调用 emplace_back, 则construct 也会得到一个右值。
eg.
svec.emplace_back(si+s2); // 使用移动构造函数//传递给 emplace_back 的实参是一个右值, 它将以如下形式传递给//std::forward<string> (string("the end" ))
forward的结果类型是 string&&, 因此 construct 将得到一个右值引用实参。 construct 会继续将此实参传递给 string 的移动构造函数来创建新元素。