_type_traits

#ifndef MY_TYPE_TRAITS_H
#define MY_TYPE_TRAITS_H
 
struct my_true_type {
};
 
struct my_false_type {
};
 
template <class T>
struct my_type_traits
{
    typedef my_false_type has_trivial_destructor;
};
 
template<> struct my_type_traits<int>
{
    typedef my_true_type has_trivial_destructor;
};
 
#endif
 
#ifndef MY_DESTRUCT_H
#define MY_DESTRUCT_H
#include <iostream>
 
#include "my_type_traits.h"
 
using std::cout;
using std::endl;
 
template <class T1, class T2>
inline void myconstruct(T1 *p, const T2& value)
{
    new (p) T1(value);
}
 
template <class T>
inline void mydestroy(T *p)
{
    typedef typename my_type_traits<T>::has_trivial_destructor trivial_destructor;                   
    _mydestroy(p, trivial_destructor());                                                                       // 判斷是否有trivial_destructor
}
 
template <class T>
inline void _mydestroy(T *p, my_true_type)
{
    cout << " do the trivial destructor " << endl;
}
 
template <class T>
inline void _mydestroy(T *p, my_false_type)
{
    cout << " do the real destructor " << endl;
    p->~T();
}
 
#endif
 
#include <iostream>
#include "my_destruct.h"
 
using std::cout;
using std::endl;
 
class TestClass
{
public:
    TestClass()
    {
        cout << "TestClass constructor call" << endl;
        data = new int(3);
    }
    TestClass(const TestClass& test_class)
    {
        cout << "TestClass copy constructor call. copy data:"
            << *(test_class.data) << endl;
        data = new int;
        *data = *(test_class.data) * 2;
    }
    ~TestClass()
    {
        cout << "TestClass destructor call. delete the data:" << *data << endl;
        delete data;
    }
private:
    int *data;
};
 
int main(void)
{
    {
        TestClass *test_class_buf;
        TestClass test_class;
 
        test_class_buf = (TestClass *)malloc(sizeof(TestClass));
        myconstruct(test_class_buf, test_class);
        mydestroy(test_class_buf);
        free(test_class_buf);
    }
 
    {
        int *int_p;
        int_p = new int;
        mydestroy(int_p);
        free(int_p);
    }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章