簡體   English   中英

統一類型和非類型模板參數

[英]Unify type and non-type template parameters

我有一個類型特征,檢查給定類型是否是給定類模板的實例:

template <template <typename...> class C, typename T>
struct check_is_instance_of : std::false_type { };

template <template <typename...> class C, typename ...Ts>
struct check_is_instance_of<C, C<Ts...>> : std::true_type { };

template <template <typename...> class C, typename T>
struct is_instance_of : check_is_instance_of<C, std::remove_cv_t<T>> { };

不幸的是,這不適用於非類型模板參數,因為它們不會被可變參數模板參數“捕獲”,因此

is_instance_of<std::integral_constant, std::true_type>

產生編譯錯誤。 有沒有辦法編寫適用於任意數量的類型和非類型模板參數的is_instance_of實現?

除非非類型參數都是相同類型並且您知道它是哪種類型, 否則我認為沒有一種干凈的方法可以做到這一點。 在這種非常特殊的情況下,可以使用函數重載。

在任何其他情況下,您最終都會遇到完美轉發問題的模板參數版本,您必須專門針對每個類型/非類型參數組合。

如果您只需要處理同類非模板參數並且您可以猜測類型,則以下內容應該有效。 您可以為不同的類型重載instance_of(這里只介紹了int),但是您必須為您希望能夠處理的每種類型顯式創建一個實例:

// variation for non-type parameters, only for uniform parameters with
// known type.
template <typename V, template <V...> class C, typename T>
struct check_is_instance_of_nontype : std::false_type { };

template <typename V, template <V...> class C, V... Values>
struct check_is_instance_of_nontype<V, C, C<Values...>> : std::true_type { };

// this is as in your example
template <template <typename...> class C, typename T>
struct check_is_instance_of : std::false_type { };

template <template <typename...> class C, typename ...Ts>
struct check_is_instance_of<C, C<Ts...>> : std::true_type { };

template <template <typename...> class C, typename T>
struct is_instance_of : check_is_instance_of<C, std::remove_cv_t<T>> { };

template <template <typename...> class C, typename T>
constexpr bool instance_of()
{
    return is_instance_of< C, T>::value;
}

template <template <int...> class C, typename T>
constexpr bool instance_of()
{
    return check_is_instance_of_nontype< int, C, T>::value;
}

template< int... >
struct Duck
{
};

template<typename A, typename B>
struct Swallow
{

};

int main() {
    typedef Duck<1, 2> SittingDuck;
    typedef Swallow< int, int> UnladenSwallow;

    std::cout << instance_of< Duck, SittingDuck>() << instance_of< Swallow, UnladenSwallow>();
    return 0;
}

暫無
暫無

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

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