简体   繁体   English

C ++中的模板类

[英]A template class in C++

What is the function of the following C++ template class? 以下C ++模板类的功能是什么? 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();
}

Is it like Java's toString() method? 它是否像Java的toString()方法?

Basically, it will take any object which has an operator<< defined for output to a stream, and converts it to a string. 基本上,它会将任何具有operator <<的输出对象定义为流,并将其转换为字符串。 Optionally, if you pass the address of a bool varaible, it will set that based on whether or not the conversion succeeeded. (可选)如果您传递bool变量的地址,它将根据转换是否成功来设置。

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. 这个函数的优点是,一旦定义了,只要你为你编写的新类定义了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 - Declares an ostringstream - an output stream that writes into a string A - 声明一个ostringstream - 一个写入字符串的输出流
  • B - Write your object into that stream, using it's operator<< B - 使用它的运算符<<将对象写入该流
  • C - Set *ok boolean to success/failure C - 将* ok布尔值设置为成功/失败
  • D - Convert the stream into a standard string & return it. D - 将流转换为标准字符串并返回。

This templated function accepts a value of any type and a pointer to a bool . 此模板化函数接受任何类型的值和指向bool的指针。 It attempts to use a std::ostringstream to convert the value to a std::string using the formatting conversions supplied by output streams. 它尝试使用std::ostringstream将值转换为std::string使用输出流提供的格式转换。 If the bool -pointer parameter is non-null, the function writes whether the stream operation succeeded to the value at that pointer. 如果bool -pointer参数为非null,则该函数会写入流操作是否成功到该指针处的值。

Thus it's possible to write: 因此可以写:

std::string s = toString(123);

But it's also possible to write: 但它也可以写:

bool succeeded;
std::string s = toString(something, &succeeded);
if (succeeded) { ... }

That is, the function allows you to check whether the conversion was successful. 也就是说,该功能允许您检查转换是否成功。

Yes and no. 是的,不是。 It works on any object for which the operator << has been defined with an ostream. 它适用于运算符<<已使用ostream定义的任何对象。 That or any object for which ostringstream has an overloaded method to handle. 那个或任何ostringstream有重载方法处理的对象。

Either the object in question that you pass into the function has the following defined: 您传递给函数的问题对象具有以下定义:

ostream& operator <<(ostream &os, MyObj &obj);

or it falls into one the standard overloads. 或者它属于一个标准的重载。 Here is a list of the overloaded functions found within `ostream' taken from here : 下面是取自`ostream的”内发现的重载函数列表, 在这里

ostream& operator<< (bool& val ); ostream&operator <<(bool&val);

ostream& operator<< (short& val ); ostream&operator <<(short&val);

ostream& operator<< (unsigned short& val ); ostream&operator <<(unsigned short&val);

ostream& operator<< (int& val ); ostream&operator <<(int&val);

ostream& operator<< (unsigned int& val ); ostream&operator <<(unsigned int&val);

ostream& operator<< (long& val ); ostream&operator <<(long&val);

ostream& operator<< (unsigned long& val ); ostream&operator <<(unsigned long&val);

ostream& operator<< (float& val ); ostream&operator <<(float&val);

ostream& operator<< (double& val ); ostream&operator <<(double&val);

ostream& operator<< (long double& val ); ostream&operator <<(long double&val);

ostream& operator<< (const void* val ); ostream&operator <<(const void * val);

ostream& operator<< (streambuf* sb ); ostream&operator <<(streambuf * sb);

ostream& operator<< (ostream& ( *pf )(ostream&)); ostream&operator <<(ostream&(* pf)(ostream&));

ostream& operator<< (ios& ( *pf )(ios&)); ostream&operator <<(ios&(* pf)(ios&));

ostream& operator<< (ios_base& ( *pf )(ios_base&)); ostream&operator <<(ios_base&(* pf)(ios_base&));

*** the following functions are not members but GLOBAL functions: ***以下函数不是成员,而是GLOBAL函数:

ostream& operator<< (ostream& out, char c ); ostream&operator <<(ostream&out,char c);

ostream& operator<< (ostream& out, signed char c ); ostream&operator <<(ostream&out,signed char c);

ostream& operator<< (ostream& out, unsigned char c ); ostream&operator <<(ostream&out,unsigned char c);

ostream& operator<< (ostream& out, const char* s ); ostream&operator <<(ostream&out,const char * s);

ostream& operator<< (ostream& out, const signed char* s ); ostream&operator <<(ostream&out,const signed char * s);

ostream& operator<< (ostream& out, const unsigned char* s ); ostream&operator <<(ostream&out,const unsigned char * s);

It's not a template class. 它不是模板类。 It's a template function/method. 这是一个模板功能/方法。 And indeed it does try to put the argument "t" into the stream. 事实上它确实试图将参数“t”放入流中。 The operation might not succeed if the output stream(ostringstream) does not support handling input of type "T"(the "<<" operator does not know how to handle objects of type T). 如果输出流(ostringstream)不支持处理类型为“T”的输入(“<<”运算符不知道如何处理类型为T的对象),则操作可能不会成功。

This is actually just a template function not a class. 这实际上只是一个模板函数而不是类。 It provides simplified semantics for converting to a string for any type that can work with an ostringstream (all numeric types will work and additional custom conversions can be defined). 它为转换为可以使用ostringstream任何类型的字符串提供了简化的语义(所有数字类型都可以工作,并且可以定义其他自定义转换)。 The function puts the value into the stream and then returns the string representation of the stream. 该函数将值放入流中,然后返回流的字符串表示形式。

First, this is not a class, it's just a function. 首先,这不是一个类,它只是一个函数。 Here's an annotated version: 这是一个带注释的版本:

// This function accepts two parameters, one of which is a constant reference
// to any arbitrary type (the arbitrary type is referred to as T), and the 
// other is an optional pointer to boolean, which is NULL if left unspecified.

template<class T> string toString(const T& t, bool *ok = NULL) {

         // This instantiates an output string stream, which is a class provided
         // by the STL which works very much like std::cout except that the output
         // is stored in a string instead of sent to standard output.

         ostringstream stream;

         // This inserts the passed-in variable t into the stream. This requires
         // that a function operator<<(ostream&, const T&) exists for the 
         // particular type T that is the type of t. If it does not exist for some
         // T that this function is called on, there will be a compile error. This 
         // operator overload is provided by default for built-in types and some STL
         // types (such as std::string). The implementation of this function for any
         // given type T is responsible for doing whatever needs to be done to 
         // represent the value of t as a character stream. This is exactly what
         // happens when you write std::cout << t, except the result is sent to
         // a string inside the stringstream instead of to the console.

         stream << t;

         // If the user passed in a pointer-to-boolean, then check if the previous
         // line caused an error, and set the boolean to false if there was an error,
         // or true otherwise. An error might occur if the value in t can't be
         // represented as a string for whatever reason.

         if(ok != NULL) *ok = stream.fail() == false;

         // This returns the string that was created by the stream (e.g. what would
         // have appeared on the terminal if stream were instead std::cout)

         return stream.str();
}

@Luna, what Wheaties mentioned is that the type of the template parameter T in your function template<class T> string toString(const T& t, bool *ok = NULL) { should either be part of the list of datatypes or the type T should implement the ostream's << operator. @Luna,Wheaties提到的是函数template<class T> string toString(const T& t, bool *ok = NULL) {中的模板参数T的类型template<class T> string toString(const T& t, bool *ok = NULL) {应该是数据类型列表或类型T的一部分应该实现ostream的<<运算符。 Else the function would fail. 否则该功能将失败。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM