Stringstream operator << for template type

I have the following code:

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

It compiles without problems with Visual C ++ on Windows, but when I try to compile it using GCC on Linux, I get the following error:

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

What could be the reason?

Thanks in advance.

+3
source share
2 answers

It depends on the type T, as indicated in Space_C0wb0y.

Check the following code

#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

}

The call ToString(empty());gives the same error as yours, but ToString(non_empty("123")); fine . What does it mean?

+4
source

Perhaps you are just missing #include<sstream>the top of the file.

, Windows - .

const char*.

0

Source: https://habr.com/ru/post/1773815/


All Articles