我目前正在为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会对无法识别它的类型做出反应, 但我需要一个固定类型才能对字符串进行更多控制。
答案 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
}
}