现在的位置: 首页 > 综合 > 正文

模板元编程练习

2013年10月19日 ⁄ 综合 ⁄ 共 633字 ⁄ 字号 评论关闭

                      编写一个一元元函数add_const_ref<T>,如果T是一个引用类型,就返回T,否则返回T const&。

#ifndef T1_H
#define T1_H

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

};

template <typename T>
struct add_const_ref<T&>
{
	typedef T type_value;

};



template <typename T>
struct is_const
{
	static const bool value = false;

};

template <typename T>
struct is_const<T&>
{
	static const bool value = true;

};





#endif
#include <iostream>
#include "t1.h"

struct A
{

};
int main()
{
   
	int i = 2;
	add_const_ref<int>::type_value j = i;
	i = j;
	std::cout << typeid(j).name() << '\n';
	std::cout << is_const<add_const_ref<A>::type_value>::value << '\n';

    return 0;
}

我使用的IDE是vs2012,结果是

vs做的还不错,结果不需要运行就可以得到了....元编程的威力发火

                    

【上篇】
【下篇】

抱歉!评论已关闭.