您的位置:首页 > 编程语言 > C语言/C++

C++11 type_traits 之is_same源码分析

2014-11-28 15:23 232 查看
请看源码:

template<typename _Tp, _Tp __v>
struct integral_constant
{
static const _Tp                      value = __v;
typedef _Tp                           value_type;
typedef integral_constant<_Tp, __v>   type;
};

/// typedef for true_type
typedef integral_constant<bool, true>     true_type;

/// typedef for false_type
typedef integral_constant<bool, false>    false_type;

template<typename, typename>
struct is_same
: public false_type { };

template<typename _Tp>
struct is_same<_Tp, _Tp>
: public true_type { };


1. is_same是模版,integral_constant也是模版

2. true_type和false_type是integral_constant实例化的类型

3.is_same通用的模版继承了false_type

4.is_same的偏特化模版继承了true_type

5.is_same模版实参类型一致时,会实例化偏特化模版,而偏特化模版继承了true_type

6.integral_constant<bool, true> 即truetype的value是true

is_same和static_assert配合使用,可以在编译期进行强大的类型检查。使用例子如下:

struct A{~A(){cout<<"delete A..."<<endl;}};
template<typename T>
struct TypeTraits
{
typedef void TYPE;
};
template<>
struct TypeTraits<std::string>
{
typedef std::string TYPE;
};
template<>
struct TypeTraits<long>
{
typedef long TYPE;
};
template<>
struct TypeTraits<A>
{
typedef A TYPE;
};
template<>
struct TypeTraits<double>
{

typedef double TYPE;
};

class DeleteLong
{
public:
void operator()(void *p)
{
delete static_cast<long*>(p);
}
};
class DeleteString
{
public:
void operator()(void *p)
{
delete static_cast<string*>(p);
}
};
class DeleteDouble
{
public:
void operator()(void *p)
{
delete static_cast<double*>(p);
}
};
class DeleteA
{
public:
void operator()(void *p)
{
delete static_cast<A*>(p);
}
};

class ExportData
{
void* vp;
enum my_type {SP,LP,DP,AP} types;
static unordered_map<type_index,my_type> typeMap;
static vector<function<void(void*)>> deleters;
public:

template <typename T> ExportData(const T& t)
{
static_assert(is_same<typename TypeTraits<T>::TYPE,T>::value,"not support!");
vp=new T(t);
types= typeMap[typeid(T)];
}
template <typename T> void setData(const T& t)
{
static_assert(is_same<typename TypeTraits<T>::TYPE,T>::value,"not support!");
assert(types==typeMap[typeid(T)]);
*(static_cast<T*>(vp))=t;
}
template <typename T> void getData(T& t)
{
static_assert(is_same<typename TypeTraits<T>::TYPE,T>::value,"not support!");
assert(types==typeMap[typeid(T)]);
t=*(static_cast<T*>(vp));
}

~ExportData()
{
(deleters[types])(vp);
}

};

unordered_map<type_index,ExportData::my_type> ExportData::typeMap
{
{typeid(string),ExportData::my_type::SP},
{typeid(long),ExportData::my_type::LP},
{typeid(double),ExportData::my_type::DP},
{typeid(A),ExportData::my_type::AP}
};
vector<function<void(void*)>> ExportData::deleters {DeleteString(),DeleteLong(),DeleteDouble(),DeleteA()};


static_assert(is_same<typename TypeTraits<T>::TYPE,T>::value,"not support!");静态断言,当用户使用不支持类型时,立即阻止用户编译。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: