如何对具有带符号数字类型的事物进行谓词
How to predicate on something having a signed numeric type?
假设我有一些模板化的代码,它执行以下操作:
T x = foo();
T y = -x;
现在,如果T是非数字类型(或者没有实现一元减号),编译就会失败。但如果它是一个无符号的int、无符号的short等,它将成功,并发出警告。所以我希望能够做
T x = foo();
if (/* magic condition */ {
T y = -x;
}
我可以写表达式来表达T的类型是某种有符号数字类型的条件吗?例如使用typeid?
注意:
- 断言也很好,但我想要更灵活的东西
C++11具有is_unsigned
特性,可以在static_assert
:中使用
#include <type_traits>
template <typename T>
void foo()
{
static_assert(std::is_unsigned<T>::value);
T x = /* ... */
T y = -x;
/* ... */
}
如果你需要更动态的检查,那么就把它放在if
条件下:
template <typename T>
void foo()
{
if (!std::is_unsigned<T>::value) {
/* To arrive here and for the following
not to error out, we must have a numeric
type that's not unsigned! */
T x = /* ... */
T y = -x;
}
else {
/* Do something else for unsigned numeric
types */
}
}
更复杂的解决方案涉及重载、std::enable_if
和各种其他模板元黑客,但以上可能就是您所需要的。
可以。
static_assert(std::is_unsigned<T>::value, "Not unsigned!");
(你需要包含type_traits才能工作。)
然后,您可以自然地调整编译过程,即使使用enable_if
,如果您确信没有其他方法:)。
相关文章:
- ArduinoJson 6.15.2:JsonObject没有命名类型
- 防止主数据类型C++的隐式转换
- 大量序列中核苷酸类型的快速计数
- 如何从C++中的依赖类型中获得它所依赖的类型
- 有关插入适配器的错误。[错误]请求从 'back_insert_iterator<vector<>>' 类型转换为非标量类型
- 是否可以初始化不可复制类型的成员变量(或基类)
- std::condition_variable::wait()如何评估给定的谓词
- 如何获取std::result_of函数的返回类型
- 从父命名空间重载类型
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- 将 unordered_map 与 Catch2 谓词一起使用时类型不匹配
- 模板类型推断失败(std::空作为谓词)
- <未解析的重载函数类型>调用二进制谓词
- 如何对具有带符号数字类型的事物进行谓词
- STL中使用的C++自定义比较类型(函数谓词与较少结构)
- 如何获取与某个谓词匹配的类型的索引
- 使用类型谓词执行重载解析
- 为什么std::copy_if签名不约束谓词类型
- C ++在我的类中condition_variable wait_for谓词,std::thread<未解析的重载函数类型>错误
- C++编译时谓词,用于测试是否可以使用 T 类型的参数调用 F 类型的可调用对象