如何解决将容器传递给可变参数模板函数
在现代 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
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。