I'm new to variadic
template functions. I have written a simple class,
StringStream
, that has a variadic template function that
creates a std::string
from variable template arguments -
strings, ints, etc.
#include
#include
class
StringStream
{
public:
StringStream() =
default;
~StringStream() = default;
template
std::string Stringify(const T
&value)
{
mStream << value;
return
mStream.str();
}
template 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
std::string Stringify(const T
&value)
{
mString +=
std::to_string(value);
return mString;
}
template<>
std::string Stringify(const
std::string& value)
{
mString += value;
}
template
std::string
Stringify(const std::string& value, Ts... values)
{
mString +=
value;
return Stringify(values...);
}
template
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?
No comments:
Post a Comment