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

时间:2016-01-14 12:25:14

标签: 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会对无法识别它的类型做出反应, 但我需要一个固定类型才能对字符串进行更多控制。

1 个答案:

答案 0 :(得分:6)

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