Skip to main content
GameDev.net gamedev.net
🔒 Locked

Template Linking Problem? [Fixed]

Started by Rob Loach Feb 16, 2005 at 3:42 PM 3 replies 1k views
Original Post
Rob Loach
Rob Loach
I made up a quick function that would attempt to use stringstream to convert any data type to a string. It all went fine and dandy, but when I attempted to split it into a .h and .cpp file, it resulted in linker crashes. ... The source has been fixed.

///////////////////////////////////
// main.cpp
#include <iostream>
#include <string>

#include "encoding.h"

using namespace std;

int main(){
	string a = ToString(4);
	cout << a << endl;
	a = ToString(543.514);
	cout << a << endl;
	cin.get();
	return 0;
}

///////////////////////////////////
// encoding.h
#if !defined(_ENCODING_H_)
#define _ENCODING_H_

#include <string>
#include <sstream>


template <class T>
std::string ToString(T data){
	std::stringstream temp;
	temp << data;
	return temp.str();
}


#endif



Results in:
[Linker error] undefined reference to `std::string ToString<int>(int)'
Anyone see what's wrong with it? (...Fixed) [Edited by - Rob Loach on February 21, 2005 4:24:37 PM]
Rob Loach [Website] [Projects] [
Prototype
Prototype
It is required that template definitions go into the .H file.
nmi
nmi
When you use templates, you have to provide some implementation for the current type.

1) include your implementation of the template class/struct/whatever at the end of your header

2) create specific implementations for known types in your .cc file
umbrae
umbrae
Template definitions and implementations can't link together so the whole implementation and definition needs to be in the .h file.

This is one of the reasons I don't like using templates, each .cpp file that uses it has to have all the code as well (from the .h file) which means duplicate code.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.