RE: Problem with function template specialization

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



 

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@xxxxxxxxxxx [mailto:gcc-help-owner@xxxxxxxxxxx] On
Behalf Of Christian Convey
Sent: 30 December 2004 11:47
To: gcc-help@xxxxxxxxxxx
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 of Archives]     [Linux C Programming]     [Linux Kernel]     [eCos]     [Fedora Development]     [Fedora Announce]     [Autoconf]     [The DWARVES Debugging Tools]     [Yosemite Campsites]     [Yosemite News]     [Linux GCC]

  Powered by Linux