可变参数模板在多个参数上给出错误

时间:2015-10-31 17:40:16

标签: c++ c++11 c++14 variadic-templates

我正在尝试http://florianjw.de/en/variadic_templates.html的代码:

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

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;
}

但是我收到以下错误:(当我将多个参数传递给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)...
     ^

我做错了什么? ideone链接:https://ideone.com/

我尝试使用ideone(gcc5.1 c++14)和Redhat 6 gcc version 4.9.1 20140922 (Red Hat 4.9.1-10)

1 个答案:

答案 0 :(得分:1)

由于T.C.没有将此作为答案发布,我将其发布在此处,以便每个人都能找到它。

ideone link

#include <tuple>
#include <initializer_list>
#include <iostream>
#include <string>
#include <vector>

template<typename Fun, typename...Ts>
void sequential_foreach(Fun f, const Ts&... args) {
  auto fun = [&](const auto& arg){f(arg); return 0;};
  (void) std::initializer_list<int>{ fun(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;
}