将整数模板参数值映射到原始类型 [英] Mapping an integral template parameter value onto a primitive type
问题描述
我想将数字映射到类型。对于此示例,我将创建一个将sizeof()结果映射到带符号原始类型的函数。
I want to map a number to a type. For this example I'll make a function that maps a sizeof() result onto a signed primitive type.
我想知道是否有更好的方法来执行我的操作下面是在现代C ++中执行的操作,它采用模板值并将其转换为类型。现在,这可以将大小转换为已知类型,但是我似乎在标准库中找不到能满足我需要的任何东西。我错过了什么吗?
I am wondering if there is a better way of doing what I did below in modern C++, which is to take a templated value and convert it into a type. Right now this works in converting a size to a known type, but I can't seem to find anything in the standard library that does what I want. Have I missed something?
如果没有,是否有更好的方法来执行此操作或清除此代码?例如,如果将来以某种方式我们最终拥有128位类型,则将不支持该类型。
If not, is there a better way of doing this or cleaning up this code? For example if somehow in the future we end up having 128 bit types, this wouldn't support that.
#include <iostream>
#include <type_traits>
template <size_t S>
static constexpr auto sizeToType() {
static_assert(S == 1 or S == 2 or S == 4 or S == 8, "Bad type size");
if constexpr (S == 1)
return int8_t{};
else if constexpr (S == 2)
return int16_t{};
else if constexpr (S == 4)
return int32_t{};
else
return int64_t{};
}
int main() {
using MY_TYPE = decltype(sizeToType<2>());
MY_TYPE myType = MY_TYPE(0xFFFFFFFFFFFFFFFEUL);
std::cout << sizeof(MY_TYPE) << " bytes" << std::endl;
std::cout << "MY_TYPE(0xFFFFFFFFFFFFFFFEUL) = " << myType << std::endl;
}
输出(预期):
2 bytes
MY_TYPE(0xFFFFFFFFFFFFFFFEUL) = -2
推荐答案
为此,我不会使用C ++ 17 constexpr
,而是使用模板专用化,
I would not use C++17 if constexpr
for this, instead I'd use template specialization, as it looks more declarative to me.
以下内容:
template<size_t S> struct SizeToType {static_assert(S != S, "Wrong size"); };
template<> struct SizeToType<1> { using type = uint8_t; };
template<> struct SizeToType<2> { using type = uint16_t; };
template<> struct SizeToType<4> { using type = uint32_t; };
template<> struct SizeToType<8> { using type = uint64_t; };
template<size_t S>
using SizeToToTypeT = typename SizeToType<S>::type;
添加更多类型只会在此处添加更多专长(单线)。
Adding more types would be just adding more specializations (one-liners) here.
这篇关于将整数模板参数值映射到原始类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!