C++ 中的模板类

发布于 2024-09-15 02:01:34 字数 320 浏览 6 评论 0原文

下面的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()方法吗?

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();
}

Is it like Java's toString() method?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

倾听心声的旋律 2024-09-22 02:01:34

基本上,它将采用任何具有运算符 << 的对象。定义用于输出到流,并将其转换为字符串。或者,如果您传递 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 布尔值设置为成功/失败
  • D - 将流转换为标准字符串 &返回它。

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.

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 - 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.
浪菊怪哟 2024-09-22 02:01:34

此模板化函数接受任何类型的值和指向bool的指针。它尝试使用 std::ostringstream 通过输出流提供的格式转换将值转换为 std::string。如果 bool 指针参数非空,则该函数将流操作是否成功写入该指针处的值。

因此可以这样写:

std::string s = toString(123);

但也可以这样写:

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

即该函数允许您检查转换是否成功。

This templated function accepts a value of any type and a pointer to a bool. It attempts to use a std::ostringstream to convert the value to a std::string using the formatting conversions supplied by output streams. If the bool-pointer parameter is non-null, the function writes whether the stream operation succeeded to the value at that pointer.

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.

不交电费瞎发啥光 2024-09-22 02:01:34

它不是模板类。这是一个模板函数/方法。
事实上,它确实尝试将参数“t”放入流中。
如果输出流(ostringstream) 则操作可能不会成功
不支持处理“T”类型的输入(“<<”运算符不支持)
知道如何处理 T 类型的对象)。

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.
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).

ㄖ落Θ余辉 2024-09-22 02:01:34

这实际上只是一个模板函数而不是一个类。它提供了简化的语义,用于将任何可以与 ostringstream 配合使用的类型转换为字符串(所有数字类型都可以使用,并且可以定义其他自定义转换)。该函数将值放入流中,然后返回流的字符串表示形式。

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). The function puts the value into the stream and then returns the string representation of the stream.

千纸鹤带着心事 2024-09-22 02:01:34

是和不是。它适用于任何使用 ostream 定义了运算符 << 的对象。 ostringstream 有要处理的重载方法的该对象或任何对象。

您传递给函数的相关对象具有以下定义:

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

或者它属于标准重载之一。以下是 `ostream' 中的重载函数列表,取自 这里

ostream&运算符<< (布尔值和值);

ostream&运算符<< (短& val);

ostream&运算符<< (无符号短整型& val);

ostream&运算符<< (int&val);

ostream&运算符<< (无符号整数&val);

ostream&运算符<< (long&val);

ostream&运算符<< (无符号长整型和值);

ostream&运算符<< (float&val);

ostream&运算符<< (双精度值);

ostream&运算符<< (long double& val);

ostream&运算符<< (const void* val);

ostream&运算符<< (streambuf* sb);

ostream&运算符<< (ostream& ( *pf )(ostream&));

ostream&运算符<< (ios& ( *pf )(ios&));

ostream&运算符<< (ios_base& ( *pf )(ios_base&));

*** 以下函数不是成员函数,而是全局函数:

ostream&运算符<< (ostream&out, char c);

ostream&运算符<< (ostream&out, 有符号的 char c );

ostream&运算符<< (ostream&out, unsigned char c);

ostream&运算符<< (ostream&out, const char* s);

ostream&运算符<< (ostream&out, constsigned char* s);

ostream&运算符<< (ostream&out, const unsigned char* s);

Yes and no. It works on any object for which the operator << has been defined with an ostream. That or any object for which ostringstream has an overloaded method to handle.

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& operator<< (bool& val );

ostream& operator<< (short& val );

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

ostream& operator<< (int& val );

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

ostream& operator<< (long& val );

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

ostream& operator<< (float& val );

ostream& operator<< (double& val );

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

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

ostream& operator<< (streambuf* sb );

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

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

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

*** the following functions are not members but GLOBAL functions:

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

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

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

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

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

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

可是我不能没有你 2024-09-22 02:01:34

首先,这不是一个类,它只是一个函数。这是一个带注释的版本:

// 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();
}

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();
}
稚气少女 2024-09-22 02:01:34

@Luna,Wheaties 提到的是函数 template中模板参数 T 的类型string toString(const T& t, bool *ok = NULL) { 应该是数据类型列表的一部分,或者类型 T 应该实现 ostream 的 <<操作员。否则该功能将失败。

@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. Else the function would fail.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文