簡體   English   中英

如何檢查類型是否為給定的模板類型

[英]How to check a type is of a given template type

我有一個模板類型:

template<class T>
struct Shadow {
   T field[100];
};

我想創建一個tuple ,其類型為Shadow實例化,但不應允許任何其他類型。 例如,

tuple< Shadow<int>, Shadow<double> > x; // correct instantiation.
tuple< Shadow<int>, double > x; // incorrect instantiation.

我怎樣才能做到這一點(並在實例化不正確的情況下讓編譯器標記一個錯誤)?

我可以想象的解決方案是將元組包裝在可變的模板結構(或類)中

#include <tuple>

template <typename T>
struct Shadow
 { T field[100]; };

template <typename ... Ts>
struct wrapTShadow
 { std::tuple<Shadow<Ts>...> val; };

int main ()
 {
   // contain a std::tuple<Shadow<int>, Shadow<double>>
   wrapTShadow<int, double>  wts;
 }

您可以使用類型別名:

template<class ...Args> 
using shadow_tuple = std::tuple<Shadow<Args>...>;

int main()
{
    shadow_tuple<int, double> xx;
    return 0;
}

暫無
暫無

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

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