[英]How to pass a templated function parameter with a subclass of the templated type in C++?
[英]How to define an enum type which includes a templated parameter ( C++ )
我想將類型 T 定義為一個枚舉,它可以取值 {A, B, C, S1, ..., Sk} 但由於 k 是一個編譯時變量,我不能只輸入它。
template <size_t k>
struct T {
enum class {
A, B, C, S_1, ..., S_k
};
};
如何定義類型?
這不是enum
但它提供了非常相似的語法(需要 C++14 或更高版本):
template<size_t k>
struct T {
struct MyEnum {
static constexpr int A = 0;
static constexpr int B = 1;
static constexpr int C = 2;
template<size_t n,
typename = typename std::enable_if<n != 0 && n <= k>::type>
static constexpr int S = Enum::C + n;
};
};
並訪問:
int test1 = T<2>::MyEnum::A;
int test2 = T<2>::MyEnum::S<2>; // Equivalent to S_2
int test3 = T<2>::MyEnum::S<3>; // Compile error: 3 > 2
int test4 = T<2>::MyEnum::S<0>; // Compile error: 0 < 1
除了尖括號之外,語法是相似的,並且都將在編譯時計算,因此沒有運行時開銷。
如果你希望這些返回一個enum
你總是可以定義你自己的並為你的enum
交換int
(缺點是你不能將struct
和enum
命名為相同的名稱)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.