将容器传递给可变参数模板函数

问题描述

在现代 C++17 中,我们如何在下面的代码中将容器(例如 std::vector)传递给可变参数模板函数

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,3 };
    foo(vec);
}

已经有人问过类似的问题:https://stackoverflow.com/a/49025839/11857122 但该解决方案使用 SFINAE。我们可以省略该机制并使用更简单的方法,例如 if constexpr 等吗?

解决方法

考虑到您的评论,这就是您可以调整代码以打印向量元素的方法

#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,3};
  foo(vec);
}

输出

1 2 3 1 2 3