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

标签 c++ templates c++11

我目前正在为 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 会对无法识别的类型使用react, 但我需要一个固定的类型才能更好地控制字符串。

最佳答案

是的,你可以!只需使用 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
    }
}

关于c++ - 你能静态地断言对象可以转换为某种类型吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34789566/

相关文章:

c++ - LD_DEBUG 输出中的 "calling init:"是什么?

c++ - XMVECTOR 类型的函数参数传递

c++ - 在 C++ 中访问继承类的特定方法

c++ - 清除任意二维数组

c++ - 默认参数和空列表初始化

c++ - 带有嵌套循环的标记元素 C++ 数组

c++ - 作为可变参数模板的结构化参数

c++ - g++ -Waddress 可能会误解我的意思

c++ - 缓存友好性 std::list 与 std::vector

C++11 编译器生成的函数