gpt4 book ai didi

c++ - 将无符号类型强制转换为 C++ 模板类型名

转载 作者:行者123 更新时间:2023-11-30 03:50:40 25 4
gpt4 key购买 nike

我是 C++ 和 template 的新手。我在 C++03 中有一个模板类,我想强制给定类型始终是无符号的。例如:

template <typename T>
class Test
{
T _var1;
};

我想强制 T 始终是 unsigned 例如 uint8_t, uint16_t, unsigned int, ... 如果给定类型是 signed。这可能在 C++ 中完成吗?如果可以,有人可以展示如何做吗?

谢谢

最佳答案

这在 C++03 中很棘手(但在 C++11 中很容易)。 Boost 提供了一种清晰可移植的方式:

#include <limits>
#include <boost/static_assert.hpp>

template <typename T>
class Test
{
BOOST_STATIC_ASSERT_MSG(std::numeric_limits<T>::is_integer &&
!std::numeric_limits<T>::is_signed,
"T must be an unsigned integer type");
// ...
};

关于c++ - 将无符号类型强制转换为 C++ 模板类型名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31616782/

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