怎么取得模板类型的成员函数

C++语言 码拜 8年前 (2016-04-24) 1081次浏览
template <class T>
struct DT {
	char unused[sizeof (T)] ;
	std::function<void (T &)> create = std::bind (&T::T ,std::placeholders::_1) ;
	std::function<void (T &)> destroy = std::bind (&T::~T ,std::placeholders::_1) ;
	inline DT () { create (reinterpret_cast <T &> (*this)) ; }
	inline ~DT () { destroy (reinterpret_cast <T &> (*this)) ; }
} ;

怎么完成这样的功能,并且DT<int>和DT<DT<int>>都可以

解决方案

30

template <class T>
struct DT {
    char unused[sizeof(T)];
    std::function<void(T &)> create = [](T & p) { new (&p) T(); };
    std::function<void(T &)> destroy = [](T & p) { p.~T(); };
    inline DT() { create(reinterpret_cast <T &> (*this)); }
    inline ~DT() { destroy(reinterpret_cast <T &> (*this)); }
};

注意不能取构造函数或析构函数的地址

10

引用:
template <class T>
struct DT {
    char unused[sizeof(T)];
    std::function<void(T &)> create = [](T & p) { new (&p) T(); };
    std::function<void(T &)> destroy = [](T & p) { p.~T(); };
    inline DT() { create(reinterpret_cast <T &> (*this)); }
    inline ~DT() { destroy(reinterpret_cast <T &> (*this)); }
};

注意不能取构造函数或析构函数的地址

++


CodeBye 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明怎么取得模板类型的成员函数
喜欢 (0)
[1034331897@qq.com]
分享 (0)