簡體   English   中英

C ++模板元編程:從模板模板參數繼承

[英]C++ Template Meta Programming: Inheritance from template template parameter

#include <type_traits>

template <typename T1, typename T2, typename is_allocated>
struct mutable_storage {};

template <
    template<typename, typename, typename> class storage_t,
    typename T2           = void,
    typename is_allocated = std::false_type
>
class Buffer : storage_t<Buffer<storage_t,void,void>, T2, is_allocated>
{};



int main() {
    typedef Buffer<mutable_storage> example_buffer;
}

這段代碼編譯(至少使用C ++ 14之后的GNU GCC編譯器)。 但是,我不喜歡使用的語法

class Buffer : storage_t<Buffer<storage_t,void,void>, T2, is_allocated>

由於它不應該要求Buffer專門化:我希望Buffer被識別為模板模板參數,如:

class Buffer : storage_t<Buffer, T2, is_allocated>

然后我希望mutable_storage結構識別模板專業化

template <typename T2, typename is_allocated>
struct mutable_storage<Buffer, T2, is_allocated> { ... };

(當然不允許,因為“緩沖區”不是類型,因此也應該更改)。 但它現在使用的方式,能夠專門使用Buffer類型感覺有點討厭。 例如,使用typedef

 typedef Buffer<storage_t, void, void> Buffer_Policy

也覺得有點討厭。 我正在尋找一種更清潔的方式。 我試圖制作一個模板模板模板參數,但是這會導致模板參數中無限量的額外模板(我不知道模板<...>到底是如何工作的,所以可能是這樣?),作為緩沖區繼承自需要另一個Buffer的東西,以便聲明storage_t。 我也嘗試使用隱式類,即inner_storage_t。 這也沒有導致成功。 有沒有人有建議,以使程序更清潔? 順便說一句,如果您發現任何其他錯誤或效率低下,請隨意提及。 感謝閱讀和可能的幫助。

由於T1僅用於模板特化選擇,因此您不必使用Buffer本身。 您可以改用標簽類型。

在命名空間中將其刪除也可以避免使用標記污染封閉命名空間的其余部分。

#include <type_traits>

template <typename T1, typename T2, typename is_allocated>
struct mutable_storage {};

namespace storage_tags {
  struct Buffer_T {};
}

template <
    template<typename, typename, typename> class storage_t,
    typename T2           = void,
    typename is_allocated = std::false_type
>
class Buffer : public storage_t<storage_tags::Buffer_T, T2, is_allocated> { 

};

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM