c++ - 如何在类级别专门化模板类

标签 c++ templates

最近有人问我一个问题。我有以下模板类:

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/

相关文章:

c++ - 寻找用于在 Linux 中高效计算巨大稀疏矩阵的 C/C++ 接口(interface)

c++ - 如何从 Int2Type 构建 Type2Int?

c++ - 为什么 C++ 容器不允许不完整的类型?

c++ - 创建类的可变包装器

c++ - 关系数据库应用

c++ - 如何在 C++ 中更改 Latin1-UTF8 编码(可能使用 Boost)?

asp.net - CSS 不会出现在一个 asp.net 页面上,在其他页面上没问题

python - 如何获得 Jinja2 模板使用的所有文件的列表?

C++ 序列点和 C++17 中求值顺序的变化

c++ - 在不知道返回类型的情况下通过地址调用 C++ 中的函数