stringstream 运算符 << 用于模板类型

rke*_*erm 3 c++ gcc templates stl

我有以下代码:

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

它在 Windows 上使用 Visual C++ 编译没有问题,但是当尝试在 Linux 上使用 GCC 编译它时,我收到以下错误:

no match for 'operator<<' in 'temp << t'
Run Code Online (Sandbox Code Playgroud)

那可能是什么原因?

先感谢您。

Pra*_*rav 5

这取决于 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

}
Run Code Online (Sandbox Code Playgroud)

要在通话ToString(empty());给出了同样的错误,你已经得到,但ToString(non_empty("123"));就是罚款。这意味着什么?