簡體   English   中英

如何使用模板模板參數專門化類模板?

[英]How to specialize a class template with a template template parameter?

我想專門針對模板模板參數的類型模板參數指定類模板。 可能嗎? 如果是,語法是什么?

#include <type_traits>

template <typename T>
struct X {};

// primary template
template<template<class> class C>
struct Z : std::false_type {};

// specialization on the template template parameter
template<>
struct Z<X> : std::true_type {}; // OK

// specialization on the type template parameter of the
// template template parameter
template <template<class> class C>
struct Z<C<int>> {}; // ERROR

動機:假設template template參數表示Collections(例如std::vectorstd::deque )。 我想專門Zstd::vector ,但我沒有興趣有關的類型模板參數std::vector ,那也無妨。 我也想專門研究所有具有int Collection類型。

該問題與以下問題類似,但它們正在嘗試專用於功能模板

還是他們試圖專門針對模板template參數

或主模板中沒有模板template參數

以下代碼可以正常編譯:

#include <type_traits>

template <typename T>
struct X {};

// primary template, no template template parameter
template<typename T>
struct Z : std::false_type {};

// specialization on the template template parameter with arbitrary T
template<typename T>
struct Z<X<T>> : std::true_type {};

// here's where you need the template template parameter
template <template<class> class C>
struct Z<C<int>> : std::true_type {};

int main()
{
    static_assert(!Z<Z<double>>::value, "" );
    static_assert( Z<Z<int   >>::value, "" );
    static_assert( Z<X<double>>::value, "" );
//  static_assert( Z<X<int   >>::value, "" ); // error: ambiguous 
                                              // partial specialization
}

在代碼中,您為Z了一個模板模板參數,即使該參數僅應用於專業化也是如此。 這就是為什么您的代碼無法編譯的原因。

這無法工作,因為在您的代碼中:

template<template<class> class C>
struct Z : std::false_type {};
template<>
struct Z<X> : std::true_type {};

Z希望將類模板作為參數。

template <template<class> class C>
struct Z<C<int>> {};

在這里,您沒有專門使用任何模板參數,而是嘗試傳遞不是類模板的C<int>C是類模板,與具體類型的C<int>不同)。

如果您的類具有template參數,這是一個類模板,並且您希望類針對傳遞給容器的不同類型表現不同,則可能應該執行以下操作:

template<template <typename> class Container,typename Element>
struct MyStruct
{
    Container<Element> generic_elements;
    // ...
};

template<template <typename> class Container>
struct MyStruct<Container,int>
{
    Container<int> special_int_container;
    void special_int_things();
    //...
};

暫無
暫無

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

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