64,654
社区成员
发帖
与我相关
我的任务
分享
Full template specialization is often useful, but sometimes it is natural to want to specialize a class template for a family of template arguments rather than just one specific set of template arguments. For example, let's assume we have a class template implementing a linked list:
template<typename T>
class List { // (1)
public:
…
void append(T const&);
inline size_t length() const;
…
};
A large project making use of this template may instantiate its members for many types. For member functions that are not expanded inline (say, List<T>::append()), this may cause noticeable growth in the object code. However, we may know that from a low-level point of view, the code for List<int*>::append() and List<void*>::append() is the same. In other words, we'd like to specify that all Lists of pointers share an implementation. Although this cannot be expressed in C++, we can achieve something quite close by specifying that all Lists of pointers should be instantiated from a different template definition:
template<typename T>
class List<T*> { // (2)
private:
List<void*> impl;
…
public:
…
void append(T* p) {
impl.append(p);
}
size_t length() const {
return impl.length();
}
…
};