Template Function Difficulties

Hi there, I am trying to create a global template function that can be used anywhere in my project. I have currently declared the function in a header file "tools.h" inside of a namespace as follows:

1
2
3
4
namespace dgTools
{
template <typename type> std::string realToString(type real);
}


The function is then defined in "tools.cpp" (which does include tools.h) as follows:

1
2
3
4
5
6
template <typename type> std::string dgTools::realToString(type real)
{
std::stringstream convert;
convert << real;
return convert.str();
}


However, when I try to call this function from another piece of code in the project, I get a Linker error (LNK2019) saying that the function (when used as a parameter in another function) is undefined. I've tried several things but I'm not sure what might be causing this error. Any help would be appreciated! Thanks!
Template declarations and definitions must be in the same file - not split across seperate files.
1
2
3
4
5
6
7
8
9
10
namespace dgTools
{
    template <typename type> std::string realToString(type real)
    {
        std::stringstream convert;
        convert << real;
        return convert.str();
    }

}


Refer to the reference documentation from this very site (see towards
the bottom of the page):
http://www.cplusplus.com/doc/tutorial/templates.html
Last edited on
Topic archived. No new replies allowed.