其他分享
首页 > 其他分享> > c-将整数模板参数值映射到原始类型

c-将整数模板参数值映射到原始类型

作者:互联网

我想将数字映射到类型.对于此示例,我将创建一个将sizeof()结果映射到带符号原始类型的函数.

我想知道是否有更好的方法可以做下面我在现代C中所做的事情,即采用模板化的值并将其转换为类型.现在,这可以将大小转换为已知类型,但是我似乎无法在标准库中找到满足我需要的内容.我错过了什么吗?

如果不是,是否有更好的方法来执行此操作或清除此代码?例如,如果将来以某种方式最终我们拥有128位类型,则将不支持该类型.

#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

解决方法:

如果使用constexpr,我不会使用C 17,而是使用模板特殊化,因为它对我来说更具声明性.

遵循以下内容:

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;

添加更多的类型只会在这里添加更多的专业化(单线).

标签:c,templates,c17
来源: https://codeday.me/bug/20191009/1881183.html