0

Before posting this, as I know It's may be a common problem, I've already read posts on StackOverflow and read about templates but I'm still not able to solve my problem.

I have a class Tool with one function inside.

.h file

class Tools{

public:
    template<typename T>
    static std::string tostr(const T& t);  

};

.cpp file

template<typename T>
std::string Tools::tostr(const T& t) {
    ostringstream os;
    os<<t;
    string res= os.str();
    return res;
}

The purpose of this function is to transform a number into a string (I know that the c++ 11 has already a function who does that but I would like to learn and to be more familiar with the concept)

In a another class, I use the function as the following:

 string resStr= Tools::tostr<string>("7.12341");

But I got this error:

error: no matching function for call to 'Tools::tostr(float)'

Then I also tried this line:

 string resStr= Tools::tostr("7.12341");

And I got also an error :

error: undefined reference to `std::string Tools::tostr(float const&)'

I don't understand because I did the following verifications:

  • I defined static in the .h file the function
  • I put the template<typename T> to define the template (I also tried with template<class T>)
  • The return type string is well defined
  • The class Tool.h is well included in the class when I call the function

Any ideas ?

Thanks you all.

lilouch
  • 1,054
  • 4
  • 23
  • 43

1 Answers1

-1

Move the definition of std::string Tools::tostr into the header file.

Oswald
  • 31,254
  • 3
  • 43
  • 68
  • In which header ? Where the function is or Where I use the function ? How I can do that ? Thanks. – lilouch Jul 15 '15 at 03:40
  • This does not provide an answer to the question. To critique or request clarification from an author, leave a comment below their post. – Mohit Jain Jul 15 '15 at 05:10
  • 1
    @lilouch Move the definition of `std::string Tools::tostr` into the header file that you mentioned in your question. Most common way to move code from one file to a different file is by Cut&Paste. – Oswald Jul 15 '15 at 09:47
  • 2
    @MohitJain I did plan to expand on that, but meanwhile R Sahu already marked the question as duplicate with a link to a perfectly fine explanation. – Oswald Jul 15 '15 at 09:53
  • Thanks ! I'll read the post. – lilouch Jul 16 '15 at 01:12