16.4节练习

练习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;
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值