练习16.51&&16.52 调用本节中的每个foo,确定sizeof...(Args)和sizeof..(rest)分别返回什么?并验证。
#include <iostream>
using namespace std;
template <typename T,typename... Args>
void foo(const T &t, const Args& ... rest)
{
cout << sizeof...(Args) << " " << sizeof...(rest) << endl;
}
int main()
{
int i = 0;
double d = 3.14;
std::string s = "hello world";
foo(i, s, 42, d);
foo(s, 42, "hi");
foo(d, s);
foo("hi");
}
练习16.53 编写你自己版本的print函数,并打印一个、两个及五个实参来测试它,要打印的每个实参都应有不同的类型。
#include <iostream>
#include <string>
using namespace std;
template <typename T>
ostream& print(ostream &os, const T &t)
{
os << t;
return os;
}
template <typename T, typename ...Args>
ostream& print(ostream &os, const T &t, const Args ...rest)
{
os << t << ", ";
return print(os, rest...);// rest...
}
template <typename T>
auto debug_rep(const T &item)->decltype(item)
{
cout << "used debug_rep" << endl;
return item;
}
template <typename ...Args>
ostream &errorMsg(ostream &os, const Args&...rest)
{
return print(os, debug_rep(rest)...);
}
int main()
{
errorMsg(cout, 1, 3.14, "string");
}
练习16.57 比较你的可变参数版本的errorMsg和198中的error_msg函数,两种方法的优缺点各是什么?
可变参数模板可以对每个元素应用模式,在多种类型中调用该函数。
练习16.58 为你的StrVec类及Vec类编写emplace_back函数。
template <typename ...Args>
void emplace_back(Args&&...rest)
{
chk_n_alloc();
alloc.construct(first_free++, std::forward<Args>(rest)...);
}
练习16.59 假定s是一个string,解释调用svec.emplace_back(s)会发生什么?
std::forward<std::string>(s)
练习16.60 解释make_shared是如何工作的。
此函数在动态内存中分配一个对象并初始化他,返回指向此对象的share_ptr。
make_shared函数一个可变参数的模板函数。
练习16.61 定义你自己版本的make_shared。
#include <iostream>
#include <memory>
#include <utility>
#include <string>
using namespace std;
template <typename T, typename ...Args>
shared_ptr<T> make_shared2(Args&& ...rest)
{
shared_ptr<T> ptr(new T(std::forward<Args>(rest)...));
cout << "used make_shared2" << endl;
return ptr;
}
int main()
{
shared_ptr<int> p1 = make_shared2<int>(1);
cout << *p1 << endl;
shared_ptr<std::string> p2 = make_shared2<std::string>("hello world");
cout << *p2 << endl;
shared_ptr<string> p3 = make_shared2<string>(10, 'c');
cout << *p3 << endl;
}