Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parameter packs with specialization for one data type

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?

like image 619
ARaj Avatar asked Sep 04 '25 16:09

ARaj


2 Answers

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).

like image 172
Walter Avatar answered Sep 07 '25 16:09

Walter


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...);
}
like image 31
Vittorio Romeo Avatar answered Sep 07 '25 17:09

Vittorio Romeo