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