1

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.

smac89
  • 39,374
  • 15
  • 132
  • 179
Blood-HaZaRd
  • 2,049
  • 2
  • 20
  • 43

1 Answers1

3

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

Brian Bi
  • 111,498
  • 10
  • 176
  • 312