简体   繁体   中英

Pass container to a variadic template function

In modern C++17, how can we pass a container such as std::vector to a variadic template function in below code?

template <typename... Args>
void foo(const Args&... args) {
    for (const auto& arg : { args... })
        std::cout << arg << ' ';
}

int main() {
    foo(1, 2, 3);
    std::vector vec{ 1, 2, 3 };
    foo(vec);
}

A similar question has been already asked: https://stackoverflow.com/a/49025839/11857122 but that solution uses a SFINAE. Can we omit that mechanism and use something easier like if constexpr etc.?

Taking your comment into consideration, this is how you can adapt your code to print the elements of the vector

#include <iostream>
#include <vector>

template <typename... Args>
void foo(const Args&... args) {
  for (const auto& arg : {args...}) {
    std::cout << arg << ' ';
  };
}

template <typename T>
std::ostream& operator<<(std::ostream& o, const std::vector<T>& v) {
  for (const auto& x : v) {
    o << x << ' ';
  }
  return o;
}

int main() {
  foo(1, 2, 3);
  std::vector vec{1, 2, 3};
  foo(vec);
}

Output

1 2 3 1 2 3

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM