0

I have some functions that don't belong to any class. So right now, they're defined in my program.cpp. Specifically, a simple

std::string to_string(double const & value){
    std::stringstream ss;
    ss << value;
    return ss.str();
}

I can use them in my classes when I declare std::string to_string(double const &);. But I can't get that to work with templates, i.e. with

template <typename T>
std::string to_string(T const & value){
    std::stringstream ss;
    ss << value;
    return ss.str();
}

In whatever way I declare it, I always end up with "undefined reference to" errors. Any way to do that? The way c++ forces bookkeeping on you makes me sad :(

Basti
  • 2,228
  • 1
  • 19
  • 25
  • Have you included `sstream` ? – davidhigh May 11 '15 at 17:24
  • Template definitions need to be included in the source that wants to use it, or explicitly instantiated. – jxh May 11 '15 at 17:24
  • It helps if you post this error. It also helps if people don't vote the question as duplicate when you are not asking about why templates can only be implemented in the header. – Alfred Rossi May 11 '15 at 17:25
  • sstream is not the issue; how would I "explicitly instantiate" such a thing? Simply putting a `std::string to_string(double const &);` doesn't work. The error messages are really just like `...xxx.cpp:(.text+0xc58): undefined reference to `to_string(double const&)'` for every time I use it. – Basti May 11 '15 at 17:28
  • Now it's a duplicate for sure. The function def (including body) needs to go into a .h file, include that .h file – Alfred Rossi May 11 '15 at 17:29

0 Answers0