C++11/14之萃取(traits)技术

萃取(traits)技术

参考网页

https://en.cppreference.com/w/cpp/types

类型萃取案例

C++11提供很多类型萃取接口,这些接口其实是一些类模板。
通过萃取接口中的value值为true,false获取信息。


#include "pch.h"
#include <iostream>
#include <vector>
#include <algorithm>
#include <map>
#include <list>
#include <unordered_set>
#include <functional>
#include <queue>

using namespace std;
//
namespace _nmsp1
{	
	template <typename T>
	void printTraitsInfo(const T& t)
	{
		cout << "--------------begin-----------" << endl;

		cout << "我们要萃取的类型名字是:" << typeid(T).name() << endl;

		cout << "is_void = " << is_void<T>::value << endl;                                    //类型是否是void
		cout << "is_class = " << is_class<T>::value << endl;                                  //类型是否是一个class
		cout << "is_object = " << is_object<T>::value << endl;                                //类型是否是 一个对象类型
		cout << "is_pod = " << is_pod<T>::value << endl;                                      //是否普通类(只包含成员变量,不包含成员函数);   POD(plain old data)
		cout << "is_default_constructible = " << is_default_constructible<T>::value << endl;  //是否有缺省构造函数
		cout << "is_copy_constructible = " << is_copy_constructible<T>::value << endl;        //是否有拷贝构造函数
		cout << "is_move_constructible = " << is_move_constructible<T>::value << endl;        //是否有移动构造函数
		cout << "is_destructible = " << is_destructible<T>::value << endl;                    //是否有析构函数
		cout << "is_polymorphic = " << is_polymorphic<T>::value << endl;                      //是否含有虚函数
		cout << "is_trivially_default_constructible = " << is_trivially_default_constructible<T>::value << endl;      //缺省拷贝构造函数是否是可有可无的(没有也行的),返回1表示确实可有可无

		cout << "has_virtual_destructor = " << has_virtual_destructor<T>::value << endl;      //是否有虚析构函数

		cout << "--------------end-------------" << endl;

	}

	class A
	{
	public:
		A() = default;
		A(A&& ta) = delete;           //移动构造:你要不写delete,系统一般就会认为你有这个成员函数;
		A(const A& ta) = delete;      //拷贝构造 
		virtual ~A() {}
	};
	class B
	{
	public:
		int m_i;
		int m_j;
	};
	class C
	{
	public:
		C(int t) {} //有自己的构造函数,编译器不会给你提供缺省构造函数
	};

	void func()
	{
		printTraitsInfo(int());     //扔一个临时对象进去
		printTraitsInfo(string());
		printTraitsInfo(A());
		printTraitsInfo(B());
		printTraitsInfo(C(1));
		printTraitsInfo(list<int>());
	}
}


int main()
{		
	_nmsp1::func();	
	
	return 1;
}
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值