c++ - C++中的模板类

标签 c++ templates tostring

下面的C++模板类的作用是什么?我在逐行注释之后:

template<class T> string toString(const T& t, bool *ok = NULL) {
         ostringstream stream;
         stream << t;
         if(ok != NULL) *ok = stream.fail() == false;
         return stream.str();
}

是不是很像Java的toString()方法?

最佳答案

基本上,它会将任何具有 operator<< 定义的对象输出到流,并将其转换为字符串。或者,如果您传递 bool 变量的地址,它将根据转换是否成功进行设置。

此函数的优点是,一旦定义,一旦为您编写的新类定义了 operator<<,您也会立即获得一个 toString() 方法。

 template<class T> 
 string toString(const T& t, bool *ok = NULL) 
 { 
         ostringstream stream;     // line A
         stream << t;              // line B
         if(ok != NULL) 
               *ok = (stream.fail() == false);  // line C
         return stream.str();      // Line D
} 
  • A - 声明一个 ostringstream - 一个写入字符串的输出流
  • B - 将您的对象写入该流,使用它的运算符<<
  • C - 将 *ok bool 值设置为成功/失败
  • D - 将流转换为标准字符串并返回。

关于c++ - C++中的模板类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3512685/

相关文章:

php - C++ 和 PHP 中的命名管道

android - eclipse 中没有 std::find() 的匹配函数。在 XCode 中运行良好

C# XMLElement.OuterXML 在一行而不是格式

c++ - 模板参数类型推导在函数对象中不起作用

rust - 如何在 Rust 中将 read_line() 的结果作为字符串获取?

c++ - 如何 'cout' double 值的正确小数位数?

c++ - 模板:我需要更好地学习这些吗?为什么我收到错误

c++ - 与C++中的delete关键字操作混淆

c++ - 点容器

c++ - 展开到 std::tuple 的可变参数模板