How do make a csv list using a fold expression?

Viewed 92

I would like to create a CSV list using a variadic function.
Being a lazy programmer, it would be nice to have it be a one-liner, and fold expressions look like they might fit the bill.

The following code does not work:

template<typename ...T>
std::string MakeCSV(T&... args) {
    std::stringstream ss;
    (ss << args << "," << ...);
    return ss.str();
}

int main() {
    std::string s1 = "one";
    std::string s2 = "two";

    std::cout << MakeCSV(s1, s2) << std::endl;
    return 0;
}

This gives:

error: binary expression in operand of fold-expression  
 (ss << args << "," << ...);  
  ~~~~~~~~~~~^~~~~~

How do I add extra parameters to a fold expression in addition to the input list itself?

1 Answers

Change (ss << args << "," << ...); into ((ss << args << ","), ...);

The first version does not unpack, because the middle expression is too complex, but the second can be unpacked because it uses the comma operator. What's even nicer is that this version does not put a "," at the end.

template<typename ...T>
std::string MakeCSV(const T&... args) {
    std::stringstream ss;
    ((ss << args << ","), ...);
    return ss.str();
}
Related