Sign in to follow this  
Rob Loach

Template Linking Problem? [Fixed]

Recommended Posts

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]

Share this post


Link to post
Share on other sites
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

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this