如何使用條件?
#include <vector>
#include <cstdint>
#include <iostream>
#include <type_traits>
template <std::size_t N>
struct foo
{
static_assert(N < 65U, "foo 64 limit");
using vType = typename std::conditional<
(N < 9U), std::uint8_t,
typename std::conditional< (N < 17U), std::uint16_t,
typename std::conditional< (N < 33U), std::uint32_t, std::uint64_t
>::type>::type>::type;
std::vector<vType> data;
};
int main()
{
static_assert(1U == sizeof(foo<1>::vType), "!");
static_assert(1U == sizeof(foo<8>::vType), "!");
static_assert(2U == sizeof(foo<9>::vType), "!");
static_assert(2U == sizeof(foo<16>::vType), "!");
static_assert(4U == sizeof(foo<17>::vType), "!");
static_assert(4U == sizeof(foo<32>::vType), "!");
static_assert(8U == sizeof(foo<33>::vType), "!");
static_assert(8U == sizeof(foo<64>::vType), "!");
// foo<65> f65; compilation error
}
或者,在一個更優雅的方式(恕我直言),你可以定義一個類型的特徵(selectTypeByDim
,在下面的例子),在列表中選擇第一個有用的類型基於
#include <tuple>
#include <vector>
#include <cstdint>
#include <climits>
#include <type_traits>
template <std::size_t N, typename T,
bool = (N <= sizeof(typename std::tuple_element<0U, T>::type)*CHAR_BIT)>
struct stbdH;
template <std::size_t N, typename T0, typename ... Ts>
struct stbdH<N, std::tuple<T0, Ts...>, true>
{ using type = T0; };
template <std::size_t N, typename T0, typename ... Ts>
struct stbdH<N, std::tuple<T0, Ts...>, false>
{ using type = typename stbdH<N, std::tuple<Ts...>>::type; };
template <std::size_t N, typename ... Ts>
struct selectTypeByDim : stbdH<N, std::tuple<Ts...>>
{ };
template <std::size_t N>
struct foo
{
static_assert(N < 65U, "foo 64 limit");
using vType = typename selectTypeByDim<N,
std::uint8_t, std::uint16_t, std::uint32_t, std::uint64_t>::type;
std::vector<vType> data;
};
int main()
{
static_assert(1U == sizeof(foo<1U>::vType), "!");
static_assert(1U == sizeof(foo<CHAR_BIT>::vType), "!");
static_assert(2U == sizeof(foo<CHAR_BIT+1U>::vType), "!");
static_assert(2U == sizeof(foo<(CHAR_BIT<<1)>::vType), "!");
static_assert(4U == sizeof(foo<(CHAR_BIT<<1)+1U>::vType), "!");
static_assert(4U == sizeof(foo<(CHAR_BIT<<2)>::vType), "!");
static_assert(8U == sizeof(foo<(CHAR_BIT<<2)+1U>::vType), "!");
static_assert(8U == sizeof(foo<(CHAR_BIT<<3)>::vType), "!");
//foo<(CHAR_BIT<<3)+1U> f65; compilation error
}
這種「向量」的用例是什麼? ['std :: bitset'](http://en.cppreference.com/w/cpp/utility/bitset)能解決你的問題嗎? –
我想排序生成的向量,所以我認爲bitset將不可行。 – eclipse
爲了給出更多的上下文:它是一個代表數十億字符串的類,其固定長度來自4個字符(基因組)的字母表。 N是字符數,最大值是32.字母4中的32個字符可以用64位表示。所以載體基本上是很多小的基因組樣本,這些樣本的大小應該是通用的。 – eclipse