Wat*_*ter 1 c++ templates c++17
我想将数字映射到一个类型.对于这个例子,我将创建一个将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;
}
Run Code Online (Sandbox Code Playgroud)
输出(如预期):
2 bytes
MY_TYPE(0xFFFFFFFFFFFFFFFEUL) = -2
Run Code Online (Sandbox Code Playgroud)
我不会使用C++ 17 if constexpr,而是使用模板特化,因为它看起来更具说明性.
以下内容:
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;
Run Code Online (Sandbox Code Playgroud)
添加更多类型只是在这里添加更多特化(单行).
| 归档时间: |
|
| 查看次数: |
147 次 |
| 最近记录: |