提问帖 请教各位。关于模板编程的学习路线应该是怎么样学啊?
c++吧
全部回复
仅看楼主
level 5
进击的D丝 楼主
听说学BOOST 需要模板基础66的。可是。。模板要怎么才能很6啊。没有想出一个学习方法。希望参考一下前辈们的方法。谢谢了
2016年12月14日 02点12分 1
level 11
比如说,山寨std里的map和sort
2016年12月14日 02点12分 2
谢谢了
2016年12月15日 01点12分
level 9
你说的是模板元编程吗。。。boost::mpl就是全部用这种玩法的。先看下面这段代码,不知楼主是否喜欢这种风格。
下面要实现的功能是对于size小于等于8的类,直接用这个类;对于size大的类用unique_ptr包着。效果:
// 相当于 int a = 0;
StorageWrapper<int>::type a = StorageWrapper<int>::construct(0);
// 相当于 std::unique_ptr<std::string> b = std::make_unique<std::string>("hahaha");
StorageWrapper<std::string>::type b = StorageWrapper<std::string>::construct("hahaha");
实际上boost::any里就用了类似的方法,我这个是简化版本,any内部是一个union,对于大对象当指针用,对于小对象直接存。
#include<memory>
template<bool cond,typename T, typename F>
struct Select{
typedef T type;
};
template<typename T, typename F>
struct Select<false, T, F>{
typedef F type;
};
template<typename T>
struct IsSmall {
static const bool value = sizeof(T) <= 8;
};
template<typename T>
struct DirectConstructor {
typedef T type;
template<typename ... Args>
inline static T construct(Args ... args){
return T(args...);
}
};
template<typename T>
struct UniquePtrConstructor {
typedef std::unique_ptr<T> type;
template<typename ... Args>
inline static type construct(Args ... args){
return std::make_unique<T>(args...);
}
};
template<typename T>
struct StorageWrapper {
typedef typename Select<
IsSmall<T>::value,
DirectConstructor<T>,
UniquePtrConstructor<T>
>::type constructor;
typedef typename constructor::type type;
template<typename ... Args>
static type construct(Args ... args){
return constructor::construct(args...);
}
};
2016年12月14日 06点12分 3
谢谢了
2016年12月15日 01点12分
level 8
自己造轮子,造一段就懂了
2016年12月14日 07点12分 4
谢谢了
2016年12月15日 01点12分
1