gpt4 book ai didi

C++ 数组类型依赖于模板类型

转载 作者:行者123 更新时间:2023-11-30 01:39:12 25 4
gpt4 key购买 nike

我有一个具有完整模板参数 N 的类。

template<unsigned int N>
class test {
}

现在我想要一个 std::vector,其整数类型尽可能小以容纳 N 位。

例如

class test<8> {
std::vector<uint8_t> data;
}

class test<9> {
std::vector<uint16_t> data;
}

class test<10> {
std::vector<uint16_t> data;
}
...

N=1N=64 是否有更好的方法?

最佳答案

使用条件怎么样?

#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
}

关于C++ 数组类型依赖于模板类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46206407/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com