你能静态断言对象可以转换为某种类型吗?

Can you statically assert that object can be converted to a certain type?

本文关键字:种类 类型 转换 静态 断言 对象      更新时间:2023-10-16

我目前正在开发 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
    }
}