Search code examples
c++templateseclipse-juno

How do I specify default non-template argument initializers in a c++ function template?


EDIT: See my own answer to this question for details. It turns out to be an Eclipse Juno bug, not a C++ problem. Nonetheless, the question still covers a useful topic for other C++ template users.

If I wish to create a template class with an argument of "template" type and other arguments of "non-temlate" types, may I.how do I specify this?

Example: An implementation or itoa() but with multiple types, padding and returning a string...

EDIT: fixed var names in definition.

   template <typename T>   std::string    Num2Str( T x, char pad = ' ', int width = 0 );
   template <typename T>   std::string    Num2Str( T x, char pad, int width )
   {
      static std::string   string;
      std::stringstream    ss;
      ss << std::setfill(pad) << std::setw(width) << x;
      string = ss.str();
      return string;
   }

EDIT: This should work across compilers/platforms, g++, VC++.


Solution

  • I think you're mixing up template params and function params. Why not just this:

    #include <sstream>
    #include <iomanip>
    
    template <typename T>   
    std::string Num2Str( T x, char pad = ' ', int width = 0 )
    {
        static std::string   string;
        std::stringstream    ss;
        ss << std::setfill(pad) << std::setw(width) << x;
        string = ss.str();
        return string;
    }
    
    void Test()
    {
        auto s1 = Num2Str( 1.0 );
        auto s2 = Num2Str( 2, '-' );
        auto s3 = Num2Str( 3.0, ' ', 3 );
    }