Problem with defining Template Function
Sep 10, 2009 at 4:53am UTC
Hello,
I receive the compiler error
Card.cpp:13: undefined reference to `std::string to_String<int>(int const&)'
from this code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
Object.h:
class Object {
public :
Object();
virtual ~Object();
virtual const string toString() const ;
};
ostream& operator <<(ostream &, const Object&);
template <class T>
string to_String(const T&);
1 2 3 4 5 6 7 8 9 10 11 12 13
Card.h:
#include "Object.h"
class Card : public Object {
protected :
int value;
public :
Card(int );
virtual ~Card();
virtual string toString();
};
1 2 3 4 5 6 7 8 9 10 11 12 13 14
Card.cpp:
#include "Card.h"
Card::Card(int value) {
value = value;
}
Card::~Card() {
}
string Card::toString() {
return to_String(value);
}
It seems as if the function call to_String(value) doesn't match with to_String(const T&), but I do not see how. Thanks for any help.
Sep 10, 2009 at 5:07am UTC
There is no code for that function. You have to supply it in the same file the template is in.
Also, your Card::Card(int) constructor does not do what you think it does. I would rename the parameter to something different.
Sep 10, 2009 at 5:12am UTC
I've defined it in a separate file here:
1 2 3 4 5 6 7 8 9 10 11
Object.cpp
#include "Object.h"
#include <sstream>
template <typename T>
string to_String(const T& object) {
stringstream string_stream;
string_stream << object;
return string_stream.str();
}
Is it ok for it to be defined there, or must it be in Object.h?
Thanks for the tip about the constructor. I'm a Java programmer, so I thought that would be correct.
Sep 10, 2009 at 5:14am UTC
You can't separate template functions like that unfortunately. It has to be in the in same file as it is used in (e.g. it needs to be the .h file).
Sep 10, 2009 at 5:31am UTC
Does this only apply for templates, or are there also other special functions that must be declared this way?
Sep 10, 2009 at 6:36am UTC
Just templates I believe.
Sep 10, 2009 at 12:43pm UTC
BTW, to_String() is equivalent to boost::lexical_cast<std::string>(). You might consider using it
instead of reinventing. (<boost/lexical_cast.hpp>, if you have it installed.)
Topic archived. No new replies allowed.