模板元编程 第二章练习(非答案)

本文介绍了C++模板元编程的实践,包括编写元函数add_const_ref,该函数在非引用类型前添加const引用,以及编写replace_type三元元函数,用于在复合类型中替换特定类型。通过示例代码和测试,展示了这两个元函数的使用和效果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

boost::add_const 对引用没有效果。。

#ifndef ITER_SWAP_H
#define ITER_SWAP_H

#include<iterator>
#include<iostream>
#include<boost\type_traits\add_const.hpp>
#include<boost\type_traits\add_reference.hpp>
#include<boost\type_traits\is_reference.hpp>


template<bool,class T>
struct doit{
	typename typedef T type;
};

template<class T>
struct doit<true,T>{
	typename typedef T type;
};


template<class T>
struct doit<false,T>{
	typename typedef boost::add_const<T>::type type1;
	typename typedef boost::add_reference<type1>::type type;
};

template<class T>
struct add_const_ref
{				  
	static const bool isR = boost::is_reference<T>::value;
	typename typedef doit<isR,T>::type type;
};


#endif

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值