【发布时间】:2016-01-28 19:27:23
【问题描述】:
我有一个如下格式的树结构:
template <typename DataType>
class Tree {
DataType *accessData() { return data; }
Tree *child1, *child2;
DataType *data;
};
template <typename DataType>
class Root : public Tree<DataType> {
// root provides storage of nodes; when it goes out of scope, the
// entire tree becomes invalid
MemoryPool<Tree> nodeStorage;
MemoryPool<DataType> dataStorage;
};
我在我的程序中使用了这个模板的各种实例。效果很好。
然而,一个实例化使用DataType,它只是一个枚举(因此它与指针大小相同!)并且因为速度至关重要(无论是在构建树时还是在访问树时),我'宁愿这个实例化直接使用枚举而不是指针。我希望代码看起来如何(不严格)的示例:
Tree<BigClass> *foo = ...;
foo->accessData()->doBigClassThings();
Tree<int> *bar = ...;
int x = 4 + bar->accessInt();
现在我当然可以只保留当前模板,但我不喜欢这种额外的指针访问,尤其是需要在根目录中分配整数。关于如何专门化模板以提供此功能或其他方法的任何想法?
我尝试过像这样专门化模板(以及无数其他方式)
template <> Tree<int> { ... }
但我只是不断收到编译错误。任何帮助将不胜感激!
【问题讨论】:
标签: c++ class templates pointers