C ++中的模板类 [英] A template class in C++
问题描述
以下C ++模板类的功能是什么?我逐行注释:
What is the function of the following C++ template class? I'm after line by line annotations:
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 c $ c>方法
Is it like Java's toString()
method?
推荐答案
基本上,它将接受任何具有运算符<<定义为输出到流,并将其转换为字符串。或者,如果您传递bool varaible的地址,则会根据转换是否成功设置。
Basically, it will take any object which has an operator<< defined for output to a stream, and converts it to a string. Optionally, if you pass the address of a bool varaible, it will set that based on whether or not the conversion succeeeded.
此函数的优点是,一旦定义,一旦定义了运算符<<对于你写的一个新类,你也默默地得到一个toString()方法。
The advantage of this function is that, once defined, as soon as you defined operator<< for a new class you write, you immedaitely also get a toString() method for it as well.
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-使用它的运算符< 将您的对象写入流中
- D - 将流转换为标准字符串&返回。
- A - Declares an ostringstream - an output stream that writes into a string
- B - Write your object into that stream, using it's operator<<
- C - Set *ok boolean to success/failure
- D - Convert the stream into a standard string & return it.
< ok boolean to success / failure
这篇关于C ++中的模板类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!