samedi 31 octobre 2015

Variadic templates give errors on more than one parameter

I am trying out the code from http://ift.tt/1PMRizL:

#include <tuple>
#include <initializer_list>
#include <iostream>

template<typename Fun, typename...Ts>
void sequential_foreach(Fun f, const Ts&... args) {
  (void) std::initializer_list<int>{
    [&](const auto& arg){f(arg); return 0;}(args)...
  };
}

template<typename...Ts>
void print_all(std::ostream& stream, const Ts&... args) {
  sequential_foreach([&](const auto& arg){stream << arg;}, args...);
}

int main()
{
  std::string s1("string1");
  std::string s2("string2");
  print_all(std::cout, s1, s2);

  return 0;
}

But I am getting the following errors: (when I pass more than one parameter to print_all)

main.cpp: In instantiation of ‘void sequential_foreach(Fun, const Ts& ...) [with Fun = print_all(std::ostream&, const Ts& ...) [with Ts = {std::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::basic_string<char, std::char_traits<char>, std::allocator<char> >}; std::ostream = std::basic_ostream<char>]::<lambda(const auto:2&)>; Ts = {std::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::basic_string<char, std::char_traits<char>, std::allocator<char> >}]’:
main.cpp:14:67:   required from ‘void print_all(std::ostream&, const Ts& ...) [with Ts = {std::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::basic_string<char, std::char_traits<char>, std::allocator<char> >}; std::ostream = std::basic_ostream<char>]’
main.cpp:21:30:   required from here
main.cpp:8:5: error: uninitialized const member ‘sequential_foreach(Fun, const Ts& ...) [with Fun = print_all(std::ostream&, const Ts& ...) [with Ts = {std::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::basic_string<char, std::char_traits<char>, std::allocator<char> >}; std::ostream = std::basic_ostream<char>]::<lambda(const auto:2&)>; Ts = {std::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::basic_string<char, std::char_traits<char>, std::allocator<char> >}]::<lambda(const auto:1&)>::<f capture>’
     [&](const auto& arg){f(arg); return 0;}(args)...
     ^

What am I doing wrong? ideone link: http://ift.tt/1jZLoiI

Aucun commentaire:

Enregistrer un commentaire