Search code examples
c++templatesc++17fold-expression

Can I use a Fold Expression in this example


I want to know if it is possible to use fold expression (and how to write it) in the example below.

#include <iostream>
#include <type_traits>
#include <typeinfo>
#include <sstream>
#include <iomanip>

template<int width>
std::string padFormat()
{
    return "";
}

template<int width, typename T>
std::string padFormat(const T& t)
{
    std::ostringstream oss;
    oss << std::setw(width) << t;
    return oss.str();
}

template<int width, typename T, typename ... Types>
std::string padFormat(const T& first, Types ... rest)
{
    return (padFormat<width>(first + ... + rest)); //Fold expr here !!!
}

int main()
{
    std::cout << padFormat<8>("one", 2, 3.0) << std::endl;
    std::cout << padFormat<4>('a', "BBB", 9u, -8) << std::endl;
    return 0;
}

I tried so far but i did not figured it out !!

Thank you.


Solution

  • I'm guessing you want to invoke padFormat on each argument and then concatenate. Thus, you must write

    return (padFormat<width>(first) + ... + padFormat<width>(rest));
    

    (The extra parentheses are required; a fold-expression must be enclosed in parentheses to be valid.)

    Coliru link