最近有人問我一個問題。我有以下模板化類:
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是班級成員。
如何在不復制所有(省略)類方法的情況下實作此類模板專業化?
uj5u.com熱心網友回復:
如何在不復制所有(省略)類方法的情況下實作此類模板專業化?
將你關心的東西抽象到它自己的 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才能訪問它。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/326456.html
