最近有人问我一个问题。我有以下模板类:
template<size_t SIZE>
class Cache
{
// A lot of class methods omitted
std::array<int, SIZE> _arr;
};
但有人可能会传递较大的大小并在堆栈上分配,从而耗尽堆栈内存。因此,您可能建议将其更改为在堆上分配:
template<size_t SIZE>
class Cache
{
// A lot of class methods omitted
std::unique_ptr<std::array<int, SIZE>> _arr;
};
但现在那些想要小数组的人将支付间接成本(我知道这是一个非常小的成本,但就问题的要点而言,请接受)。
因此,有人向我暗示,模板专门化可以允许一些人选择小型 std::array
实现,而另一些人则可以在堆上分配数组。
我认为这种特化必须在类级别,因为 std::array
是类成员。
如何在不复制所有(省略的)类方法的情况下实现此类模板特化?
最佳答案
How is this class template specialization achieved without duplicating all the (omitted) class methods?
将你关心的东西抽象到它自己的 mixin 类中。例如:
template<size_t SIZE, bool> // default case, condition is false
class storage {
std::unique_ptr<std::array<int, SIZE>> _arr;
protected:
// constructor too...
std::array<int, SIZE>& arr() { return *_arr; }
};
template<size_t SIZE> // special case, condition is true
class storage<SIZE, true> {
std::array<int, SIZE> _arr;
protected:
// constructor too...
std::array<int, SIZE>& arr() { return _arr; }
};
然后简单地让缓存使用它作为基础,同时检查 SIZE 的阈值:
template<size_t SIZE>
class Cache : private storage<SIZE, (SIZE < THRESHOLD)>
{
// A lot of class methods omitted
// They now use this->arr();
};
您也可以选择组合。在这种情况下,特化几乎相同,但 arr() 需要公开,以便 Cache 可以访问它。
关于c++ - 如何在类级别专门化模板类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69591445/