【问题标题】:stringstream operator << for a template typestringstream 运算符 << 用于模板类型
【发布时间】:2010-11-09 11:09:02
【问题描述】:

我有以下代码:

template <class T>
static std::string ToString(const T& t)
{
  stringstream temp;
  temp << t;
  return temp.str();
}

在 Windows 上使用 Visual C++ 编译没有问题,但在 Linux 上尝试使用 GCC 编译时出现以下错误:

no match for 'operator<<' in 'temp << t'

这可能是什么原因?

提前谢谢你。

【问题讨论】:

  • 这取决于T 的类型。这是什么?

标签: c++ templates gcc stl


【解决方案1】:

这取决于 Space_C0wb0y 所说的类型 T。

查看以下代码

#include <sstream>
#include <iostream>

template<typename T>
static std::string ToString(const T& t){
  std::stringstream temp;
  temp << t;
  return temp.str();
}
struct empty{};
struct non_empty{
  std::string str;
  non_empty(std::string obj):str (obj){}
  friend std::ostream& operator << (std::ostream& out, const non_empty &x);
};

std::ostream& operator << (std::ostream& out, const non_empty &x){
    out << x.str;
    return out;
}

int main(){
   std::string s = ToString<double>(12.3); // this will work fine
 /*********************************************************************************
  * std::string k = ToString(empty()); // no match for 'operator<<' in 'temp << t'*
  *********************************************************************************/
   std::string t = ToString(non_empty("123")); // this works too

}

ToString(empty()); 的调用给出了与您遇到的相同的错误,但ToString(non_empty("123"));fine。这意味着什么?

【讨论】:

    【解决方案2】:

    您可能只是缺少文件顶部的#include&lt;sstream&gt;

    这可以解释为什么相同的代码可以在 Windows 上编译,因为标准头文件之间存在差异。

    这是我的解决方案,当使用 const char* 类型的模板时。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-03-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-14
      • 1970-01-01
      • 2019-01-06
      相关资源
      最近更新 更多