提问人:AnnikGet 提问时间:5/2/2023 最后编辑:Brian61354270AnnikGet 更新时间:5/2/2023 访问量:65
如何将模板类型修改为无符号?
How to modify template type to be unsigned?
问:
template<class T>
void foo(T s)
{
unsigned T x = -1;
//...
}
{
int x = 129;
foo(x);
}
如何将模板类型修改为无符号? 我知道这是不好的做法,因为并非所有内容都可以宣布为未签名,但在特殊情况下这是有道理的。
我不想将修改后的类型作为模板参数传递。我想修改函数体本身中的类型。
答:
1赞
Brian61354270
5/2/2023
#1
可以使用 std::make_unsigned
检索与整数类型对应的无符号类型。
#include <type_traits>
static_assert(
std::is_same_v<
unsigned int,
std::make_unsigned_t<int>
>
);
请注意,如果模板参数不是接受的枚举有效类型之一,则程序将格式不正确/表现出未定义的行为。T
std::make_unsigned
下一个:解析的字符串可追溯到日期
评论