c++模板元编程2

c++模板元编程第二章练习题

2-0. 编写一个一元元函数add_const_ref<T>,如果T是一个引用类型,就返回T,否则返回T
const&。编写一个程序来测试你的元函数。提示:可以使用boost::is_same来测试结果。

这个比较简单:

template<typename T>
	struct add_const_ref
	{
		typedef T const& type;
	};

	template<typename T>
	struct add_const_ref<T&>
	{
		typedef T& type;
	};
测试代码:

void fun_add_const_ref()
{
	typedef const int Cint;
	typedef const int& CRint;

	typedef int& Rint;
	if (boost::is_same<Rint, add_const_ref<Rint>::type>::value)
	{
		std::cout << "true\n\n";
	}
	else
	{
		std::cout << "false\n\n";
	}

	if (boost::is_same<CRint, add_const_ref<Cint>::type>::value)
	{
		std::cout << "true\n\n";
	}
	{
		std::cout << "false\n\n";
	}
}



2-1. 编写一个三元元函数replace_type<c,x,y>,它接收一个任意的复合类型c作为其第一个参数,
并将c中出现的所有type x替换为y:
typedef replace_type< void*, void, int >::type t1; // int*
typedef replace_type<
int const*[10]
, int const
, long
>::type t2; // long* [10]
typedef replace_type<
char& (*)(char&)
, char&
, long&
>::type t3; // long& (*)(long&)
你可以将所操作的函数类型限制为具有少于两个参数的函数。

这个比较复杂:

分为4步解决

1. 首先判断c中是否含有类型x

2.如果有替换

3没有就返回元类型

4考虑一些模板特化

template<typename U, typename T>
struct is_same: boost::mpl::bool_<false>
{

};//#1

template<typename T>
struct is_same<T, T> : boost::mpl::bool_<true>
{

};//#1

template<typename TC, typename TX, typename TY, bool same>
struct replace_type_imp;//#2
template<typename TC, typename TX, typename TY> 
struct replace_type
{
	static bool const value = is_same<TC, TX>::value;//#3
	typedef typename replace_type_imp<TC, TX, TY, value>::type type;//#4
};
#1判断两个类型时候为同一个类型 如果是返回true,否则返回false

#2replace_type的具体实现,包含一个特化情况

#3返回时候相同value记录返回结果

#4根据vlaue的值返回类型

下面是一般类型的实现:

特化void
//TC:void const*, TX:void const
template<typename TC, typename TX, typename TY>
struct replace_type_imp<TC(), TX, TY, false>
{
	typedef typename replace_type<TC, TX, TY>::type type();
};

//特化TC*
//TC:int const*, TX:int const
template<typename TC, typename TX, typename TY>
struct replace_type_imp<TC*, TX, TY, false>
{
	typedef typename replace_type<TC, TX, TY>::type* type;
};

//特化TC&
//TC::int const&, TX:int const
template<typename TC, typename TX, typename TY>
struct
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 5
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值