Does std::stringstream know templates

  • Thread starter Rene Ivon Shamberger
  • Start date
R

Rene Ivon Shamberger

Does std::stringstream work with templates, say for instance

void someMethod(int i){
std::string s;
std::stringstream out;
out << i;
s = out.str();
....
}
could be written like this:
template< typename T>
void someMethod(const T& data){
std::string s;
std::stringstream out;
out << data; //<<-- here is the majic would-be :(
s = out.str();
....
}
However, it seems that std::stringstream does not know templates, or does it. Maybe I am writing the code wrong! Any body?


TIA
 
I

Ian Collins

Rene said:
Does std::stringstream work with templates, say for instance

void someMethod(int i){
std::string s;
std::stringstream out;
out << i;
s = out.str();
....
}
could be written like this:
template< typename T>
void someMethod(const T& data){
std::string s;
std::stringstream out;
out << data; //<<-- here is the majic would-be :(
s = out.str();
....
}
However, it seems that std::stringstream does not know templates, or does it. Maybe I am writing the code wrong! Any body?

Provided T has an appropriate stream operator, this will work.
 
N

Nobody

However, it seems that std::stringstream does not know templates, or
does it. Maybe I am writing the code wrong! Any body?

Anything which works in non-template code will work in a template,
provided that the template can be instantiated.

Your example will work fine for any type for which an appropriate
operator<< exists (either as method or a function). I've used a
similar template on many occasions.

If your code doesn't work for some particular case, it's probably because
no suitable operator<< can be found.
 
R

Rui Maciel

Rene said:
Does std::stringstream work with templates, say for instance

void someMethod(int i){
std::string s;
std::stringstream out;
out << i;
s = out.str();
....
}
could be written like this:
template< typename T>
void someMethod(const T& data){
std::string s;
std::stringstream out;
out << data; //<<-- here is the majic would-be :(
s = out.str();
....
}
However, it seems that std::stringstream does not know templates, or does
it. Maybe I am writing the code wrong! Any body?

The std::stringstream class works fine.

What did you expected your code would do? And can you provide an example
that reproduces the problem you've been experiencing?


Rui Maciel
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Members online

Forum statistics

Threads
473,768
Messages
2,569,574
Members
45,050
Latest member
AngelS122

Latest Threads

Top