【问题标题】:Pass container to a variadic template function将容器传递给可变参数模板函数
【发布时间】:2021-03-22 17:19:02
【问题描述】:

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

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

【问题讨论】:

  • std::cout &lt;&lt; std::vector 究竟会做什么?如果您删除该行,则编译得很好,没有定义向量的&lt;&lt; 运算符
  • 我不想打印 std::vector 本身。我想打印 std::vector 的元素。

标签: c++ c++17 variadic-templates variadic-functions sfinae


【解决方案1】:

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

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

输出

1 2 3 1 2 3

【讨论】:

    猜你喜欢
    • 2014-10-20
    • 2011-11-15
    • 1970-01-01
    • 2011-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-27
    • 2015-09-07
    相关资源
    最近更新 更多