This is the mail archive of the gcc-help@gcc.gnu.org mailing list for the GCC project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

RE: Problem with function template specialization


 

To make it compile do the following:

1) Add a new type(alias) that is a pointer to Foo.

typedef Foo* FooP;

2) Change your specialisation to use this new Type (and remove const
from the specialisation <>)

template <> 
string toString<FooP>(const FooP& p) {
                ^^^^
NB. No const in here


-----Original Message-----
From: gcc-help-owner@gcc.gnu.org [mailto:gcc-help-owner@gcc.gnu.org] On
Behalf Of Christian Convey
Sent: 30 December 2004 11:47
To: gcc-help@gcc.gnu.org
Subject: Problem with function template specialization

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;
}



Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]