Search code examples
c++c++11tostring

Overloading standard C++ library functions inside a templated class file


I'm trying to overload std::to_string() function to where it can take a string as its argument and just return the string, in the same file as a templated class. This is so it can be used by the member functions. But it's gicing me the error: out-of-line definition of 'to_string' does not match any declaration in namespace 'std'

Here's a generalized version of what I'm going for:

#include <string>
using namespace std;

string std::to_string(string str){return str;}

template <class Type>
class myClass
{
    public:
        int getPrintLength(Type var);
};

template <class Type>
int myClass<Type>::getPrintLength(Type var)
{
    return to_string(var).size();
}

For context, I'm doing this so that I can get the number of characters a variable (of any standard type) would have if printed, including string, via to_string(var).size(), which requires the function to take strings as an argument (so I don't have to check what type the variable is).

But of course, there may be a better way of doing this, to which I am open.

I have tried using different scopes, and templating my to_string() overload (using template<> instead of my usual template<class Type>). These resulted in the class simply using the overload and never the standard C++ function, and a no function template matches function template specialization 'to_string' error respectively.


Solution

  • You can write a separate to_string() function for string input. Compiler will take care of calling your to_string() or std::to_string() based on the input type.

    using namespace std;
    
    string to_string(std::string str){
        return str;
    }
    
    template <class Type>
    class myClass
    {
        public:
        int getPrintLength(Type var);
    };
    
    template <class Type>
    int myClass<Type>::getPrintLength(Type var){
        return to_string(var).size();
    }
    int main(){
        myClass<int> myInt;
        myClass<std::string> var;
        cout<<myInt.getPrintLength(1235)<<endl;
        cout<<var.getPrintLength("StarRocket")<<endl;
    }