gpt4 book ai didi

c++ - 在 C++ 中创建模板化结构或从整数键到变量类型的映射

转载 作者:行者123 更新时间:2023-11-28 05:07:03 25 4
gpt4 key购买 nike

我面临的问题是,我将一些数据存储在未知类型的数组 array 中。然而,函数 array_getDataType() 给定数组返回一个整数,例如 UBIT8 其中 UBIT8 是在某处定义的常量,这基本上意味着数组中存储的元素类型为unsigned char。我想知道是否有某种方法可以在这些定义的常量和实际类型之间创建一个映射,这种映射接受“BIT8”并返回“unsigned char”。我知道有一种方法可以通过以下方式对模板进行相反的操作。

template< typename T >
struct type2Int
{
enum { id = 0 };
};
template<> struct type2Int<unsigned char> { enum { id = UBIT8 }; };

这以后可以用作

type2Int<unsigned char> type;

然后

type.id 

将是 UBIT8 的定义,我想知道如何做相反的事情。

最佳答案

I was wondering how to do the opposite.

以类似的方式,使用模板特化。

举例

#include <iostream>

template <std::size_t>
struct int2type;
// { using type = void; }; ???

template <>
struct int2type<0U>
{ using type = char; };

template <>
struct int2type<1U>
{ using type = int; };

template <>
struct int2type<2U>
{ using type = long; };

int main()
{
static_assert(std::is_same<typename int2type<0>::type, char>::value, "!");
static_assert(std::is_same<typename int2type<1>::type, int>::value, "!");
static_assert(std::is_same<typename int2type<2>::type, long>::value, "!");
}

如果你不能使用 C++11(所以没有 using),你可以使用旧的 typedef

template <std::size_t>
struct int2type;

template <>
struct int2type<0U>
{ typedef char type; };

// ...

关于c++ - 在 C++ 中创建模板化结构或从整数键到变量类型的映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44458112/

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