Problem with function template specialization

Christian Convey conveycj@npt.nuwc.navy.mil
Thu Dec 30 16:48:00 GMT 2004


Hello,

I'm trying to write a small library of function templates, all named 
"toString", that will produce a string rendition of various data types.

My problem is that when I try to create a specialized version of the 
toString() function for a particular data type, I get an error:

~$ g++ problem.cpp
problem.cpp:24: error: template-id `toString<const Foo*>' for `std::string
    toString(const Foo*)' does not match any template declaration
problem.cpp:24: error: syntax error before `{' token
problem.cpp:26: error: syntax error before `<<' token
problem.cpp:33:2: warning: no newline at end of file


Can anyone suggest where I've gone wrong?

Thanks very much,
Christian
-- 
Christian Convey
Computer Scientist,
Naval Undersea Warfare Center
Newport, RI


Here's the code:
================

#include <iostream>
#include <sstream>
#include <vector>
#include <string>

using namespace std;

struct Foo {
   int x;
   int y;
};

// for any class that ostringstream knows how
// to render...
template <typename T>
string toString(const T& val) {
   ostringstream os;
   os << val;
   return os.str();
}

// For pointers to Foo objects...
template <>          // *** THIS IS LINE 24 ***
string toString<const Foo*>(const Foo* p) {
   ostringstream os;
   os << "(" << p << ") = Foo(" << p->x << ", " << p->y << ")";
   return os.str();
}

int main() {
   Foo f;
   cout << toString(& f) << endl;
}



More information about the Gcc-help mailing list