gpt4 book ai didi

c++ - 根据最大可能数在编译时确定索引类型

转载 作者:太空狗 更新时间:2023-10-29 23:44:49 26 4
gpt4 key购买 nike

我正在尝试制作 index_type_<N>将返回 type 的类型基于 N 的索引其中 N是索引可以到达的最大数目。

例如:

index_type_<32>::type index1; //uint8_t
index_type_<64000>::type index2; //uint16_t
index_type_<18446744073709551>::type index3; //uint64_t

我有以下拒绝编译的代码,尽管在错误消息上搜索谷歌,但我无法确定原因,它们似乎与我的情况无关。

    #include <iostream>

template<size_t N, typename T = void>
struct index_type_;

template<size_t N>
struct index_type_<N, typename std::enable_if<N <= 256, uint8_t>::value>
{
typedef uint8_t type;
};
template<size_t N, typename T = void>
struct index_type_;

template<size_t N>
struct index_type_<N, typename std::enable_if<N <= 65536, uint16_t>::value>
{
typedef uint16_t type;
};

template<size_t N>
struct index_type_<N, typename std::enable_if<N <= 4294967296, uint32_t>::value>
{
typedef uint32_t type;
};

template<size_t N>
struct index_type_<N, typename std::enable_if<N <= 18446744073709551616ULL, uint64_t>::value>
{
typedef uint64_t type;
};

int main()
{
index_type_<32>::type index1;
index_type_<232122>::type index2;
index_type_<992532523>::type index3;
index_type_<4213662352328854>::type index4;

std::cout << "index1:" << sizeof(index1) << std::endl;
std::cout << "index2:" << sizeof(index2) << std::endl;
std::cout << "index3:" << sizeof(index3) << std::endl;
std::cout << "index4:" << sizeof(index4) << std::endl;
}

可以在此处找到错误和示例代码:

http://ideone.com/SJdKjr

非常感谢任何帮助,我觉得我遗漏了一些明显的东西。

最佳答案

你所有的特化都是模棱两可的。例如。以下哪一项是最佳选择?

template <std::size_t N>
struct Foo {
// Specialization 1
};

template <std::size_t N>
struct Foo<N> {
// Specialization 2
};

int main() {
Foo<1> foo; // Error: partial specialization 'Foo<N>' does not
// specialize any template arguments.
}

尝试这样的事情:

template <std::uintmax_t N>
struct index_type {
using type = std::conditional_t<N <= 255, std::uint8_t,
std::conditional_t<N <= 63535, std::uint16_t,
std::conditional_t<N <= 4294967295, std::uint32_t,
std::conditional_t<N <= 18446744073709551615ULL, std::uint64_t,
std::uintmax_t>>>>;
};

template <std::uintmax_t N>
using index_type_t = typename index_type<N>::type;

用法:

index_type_t<64000> test; // unsigned int

关于c++ - 根据最大可能数在编译时确定索引类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24466278/

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