你能静态断言对象可以转换为某种类型吗?
Can you statically assert that object can be converted to a certain type?
我目前正在开发 C++11 的控制台 GUI 库,只是为了简化一些调试和其他事情。
对于模板的某个类,我想确保我可以在打印之前将模板化类型转换为字符串。
例:
template<typename T>
class listbox {
private:
std::vector<T> list;
[...]
public:
std::string print_item(T& item) { /* static_assert() here */}
}
因此,在"静态断言"部分中,我想检查是否可以将项目转换为std::string
(或者const char*
也可以),所以问题实际上很简单,如何断言从模板类型的转换?
我知道编译器/ide 会对无法识别它的类型做出反应,但我需要一个固定的类型才能更好地控制字符串。
是的,你可以!只需使用std::is_convertible
template<typename T>
class listbox {
private:
std::vector<T> list;
[...]
public:
std::string print_item(T& item) {
static_assert(std::is_convertible<T, const char*>::value, "Not stingifyable");
// More work
}
}
相关文章:
- ArduinoJson 6.15.2:JsonObject没有命名类型
- 防止主数据类型C++的隐式转换
- 大量序列中核苷酸类型的快速计数
- 如何从C++中的依赖类型中获得它所依赖的类型
- 有关插入适配器的错误。[错误]请求从 'back_insert_iterator<vector<>>' 类型转换为非标量类型
- 是否可以初始化不可复制类型的成员变量(或基类)
- 如何获取std::result_of函数的返回类型
- 从父命名空间重载类型
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- 我想将一个对T类型的非常量左值引用绑定到一个T类型的临时值
- Openssl 1.1.1d无效使用不完整的类型"struct dsa_st"
- 访问者访问变体并返回不同类型时出错
- 在VS2010-VS2015下编译时,如何使用decltype作为较大类型表达式的LHS
- 处理小于cpu数据总线的数据类型.(c++转换为机器代码)
- C++ 雷神库 - 使用资源加载器类时出现问题(不命名类型)
- 模板元程序查找相似的连续类型名称
- 任何种类的分数 在任何类型的订单中
- 2 种模板相关类型种类的差异
- C++每帧更新和复制一系列值.我应该使用哪种类类型
- 在键上使用 map.find() 和 count(),这是一种类对象类型