vendredi 6 septembre 2019

Variadic template function to create string

I'm new to variadic template functions. I have written a simple class, StringStream, that has a variadic template function that creates a string from variable template arguments - strings, ints, etc.

#include <string>
#include <sstream>

class StringStream
{
public:
    StringStream() = default;
    ~StringStream() = default;

    template<typename T>
    std::string Stringify(const T &value)
    {
        mStream << value;
        return mStream.str();
    }

    template<typename T, typename... Ts>
    std::string Stringify(const T& value, Ts... values)
    {
        mStream << value;
        return Stringify(values...);
    }

private:
    std::stringstream mStream;
};

What I want to do now is use a std::string member in StringStream instead of std::stringstream and build the string from the arguments of Stringify. For arguments that are not std::string I want to convert to strings with std::to_string(), otherwise I just concatenate the argument. I am running into a compiler error. Here's my modified class:

class StringStream
{
public:
    StringStream() = default;
    ~StringStream() = default;

    template<typename T>
    std::string Stringify(const T &value)
    {
        mString += std::to_string(value);
        return mString;
    }

    template<>
    std::string Stringify<std::string>(const std::string& value)
    {
        mString += value;
    }

    template<typename... Ts>
    std::string Stringify(const std::string& value, Ts... values)
    {
        mString += value;
        return Stringify(values...);
    }

    template<typename T, typename... Ts>
    std::string Stringify(const T& value, Ts... values)
    {
        mString += std::to_string(value);
        return Stringify(values...);
    }

private:
    std::string mString;
};

My compiler error says:

error C2665: 'std::to_string': none of the 9 overloads could convert all the argument types

I am calling the function like this:

int main()
{
    int age;
    std::cin >> age;
    StringStream ss;
    std::cout << ss.Stringify("I", " am ", age, " years ", "old") << std::endl;
}

Is there any way to resolve this?

Aucun commentaire:

Enregistrer un commentaire