Jump to content
  • Advertisement
Sign in to follow this  
Rob Loach

Template Linking Problem? [Fixed]

This topic is 4900 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

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
Advertisement
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
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!