Converting an integer to a string

Started by
5 comments, last by Crazyfool 17 years, 2 months ago
Hi all, I need to convert an integer to a string. The member "level" of the class "bot" is a list[20]. This is my code:

string number = "number=" + itos(bot[numero].levels[j].size());



template <class X>
string itos(const X i)	// convert int to string
{
	std::stringstream s;
	s << i;
	return s.str();
}


And in the header file:

template <class X>
std::string itos(const X);


The problem is I get some error LNK2019: "external symbols not resolved". I know I can use itoa to, but it seems using a function like this is easier. Thanks for your help.
Advertisement
You can't do that with templates without support for the export keyword. You'll either need to include the definition in the header file, or include the .cpp file into the header.

[Edited by - Washu on February 14, 2007 1:39:20 PM]

In time the project grows, the ignorance of its devs it shows, with many a convoluted function, it plunges into deep compunction, the price of failure is high, Washu's mirth is nigh.

Quote:Original post by Washu
You can't do that with templates without support for the extern keyword. You'll either need to include the definition in the header file, or include the .cpp file implementation file, which should be renamed to something not ending with .cpp into the header.


Fixed. I would use something along the lines of .impl.hpp, since your IDE is probably already configured to treat .hpp files as C++ code. But #including .cpp files is just asking for more linker troubles -- namely, duplicate symbol errors the moment you define a non-template function/variable in the .cpp file, as people usually expect to be able to do with .cpp files.

...if it wasn't already obvious, you'll also have to put any of the aforementioned non-template function/variables into a different file, for the exact aforementioned reasons :).
Thank you very much. The problem has been solved.

Thanks.
Isn't there an export keyword for doing this kind of job? Although, I am not sure if the keyword is compiler specific.
Quote:Isn't there an export keyword for doing this kind of job? Although, I am not sure if the keyword is compiler specific

Quote:You can't do that with templates without support for the export keyword. You'll either need to include the definition in the header file, or include the .cpp file into the header.
(Emphasis added)

the problem is its only supported by one compiler (EDG iirc)

[Edited by - Washu on February 14, 2007 1:35:40 PM]
Maybe I have just written so many toStr() functions, but now, without including ANYTHING (maybe I have a default include?)

I do toStr( and then VC2005EE shows that its a method and I do it and bam. Maybe I',m just high =(

This topic is closed to new replies.

Advertisement