『STLソース剖析』ノート:traits技術
3407 ワード
template
struct my_is_void
{
static const bool value = false;
};
template <>
struct my_is_void
{
static const bool value = true;
};
cout << my_is_void::value << endl;
cout << my_is_void::value << endl;
上の例は,テンプレート偏特化およびクラス静的変数を用いて,タイプに対する空タイプ判定を実現した例である.template
void func(Iterator iter)
{
// ?
*iter var // 。
}
//
template
void func(Iterator iter)
{
__func(&*iter);
}
template
void __func(T* )
{
T var;
}
template
inline void destory(ForwardIterator first, ForwardIterator last)
{
if (is_POD_type(*first))
; // int POD_type , 。
if (is_no_POD_type(*first))
for (; first != last; first++)
first->~(*first)() // ,(*first) 。
}
を解析することを目的としているが、is_POD_typeとis_no_POD_typeの2つの意味をどのように表現するか.この場合、埋め込み型別とバイアス化で実現できる.//
struct _true_type { };
struct _false_type { };
// POD_type
template
struct _type_traits
{
typedef _false_type has_trivial_default_constructor;
typedef _false_type has_trivial_copy_constructor;
typedef _false_type has_trivial_assignment_operator;
typedef _false_type has_trivial_destructor;
typedef _false_type is_POD_type;
};
// char
template<>
struct _type_traits
{
typedef _true_type has_trivial_default_constructor;
typedef _true_type has_trivial_copy_constructor;
typedef _true_type has_trivial_assignment_operator;
typedef _true_type has_trivial_destructor;
typedef _true_type is_POD_type;
};
// int
template<>
struct _type_traits
{
typedef _true_type has_trivial_default_constructor;
typedef _true_type has_trivial_copy_constructor;
typedef _true_type has_trivial_assignment_operator;
typedef _true_type has_trivial_destructor;
typedef _true_type is_POD_type;
};
...... POD 。
// non trivaial destructor。
template
inline void destory(ForwardIterator first, ForwardIterator last)
{
/* _type_traits */
typedef typename _type_traits::is_POD_type is_POD_type;
__destory_aux(first, last, is_POD_type());
}
// trivial destructor,
template
inline void __destory_aux
(ForwardIterator first, ForwardIterator last, _true_type)
{
}
// non trivial destrouctor, destroy
template
inline void __destory_aux(ForwardIterator first, ForwardIterator last,
_false_type)
{
for (; first != last; ++first)
destory(&*first);
}
// destroy
template
inline void destory(T* pointer)
{
pointer->~T();
}