I have below code to convert all arguments passed to a function into csv:
void Parse(ostream& os)
{
}
template <typename T, typename... Args>
void Parse(ostream& os, T t, Args... args)
{
os << *t << ',';
Parse(os, args...);
}
While this works fine for all data types for what I am doing, I want some special handling for char data types. If there is a char parameter(for eg. 0) I want to convert it into ascii(48 for zero) and then add it to the csv. I cannot modify it at the caller place. How can I handle it in the parameter pack?
You just define an overloaded function (details::print()
in the example below) for dealing with a single datum and then join them using a fold expression:
namespace details {
template<typename T>
void print(std::ostream&os, T const&x)
{ os << x << ','; } // print any value
template<typename T>
void print(std::ostream&os, T*x)
{ print(os,*x); } // print value pointed to
template<typename T>
void print(std::ostream&os, const T*x)
{ print(os,*x); } // print value pointed to
void print(std::ostream&os, const char*x)
{ os << x << ','; } // print C-style string
}
template<typename...Args>
void parse(std::ostream&os, const Args& ...args)
{
(details::print(os,args) , ...); // fold expression
}
int main()
{
double x=3.1415;
parse(std::cout,"fun",42,'d',&x);
}
output: fun,42,d,3.1415,
You can suppress the trailing comma by the method of Jarod's answer (though your original post didn't suppress it).
template <typename T, typename... Args>
void Parse(ostream& os, T t, Args... args)
{
if constexpr(std::is_same_v<T, char>)
{
os << to_ascii(t) << ',';
}
else
{
os << *t << ',';
}
Parse(os, args...);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With