【发布时间】:2014-05-03 19:50:43
【问题描述】:
在学习模板参数包时,我正在尝试编写一个聪明、简单的函数来有效地将两个或多个std::vector 容器附加在一起。
以下是两个初始解决方案。
版本 1 优雅但有缺陷,因为它依赖于参数包扩展过程中的副作用,并且评估顺序未定义。
版本 2 有效,但依赖于需要两种情况的辅助函数。呸。
你能想出一个更简单的解决方案吗? (为了效率,向量数据不应该被复制超过一次。)
#include <vector>
#include <iostream>
// Append all elements of v2 to the end of v1.
template<typename T>
void append_to_vector(std::vector<T>& v1, const std::vector<T>& v2) {
for (auto& e : v2) v1.push_back(e);
}
// Expand a template parameter pack for side effects.
template<typename... A> void ignore_all(const A&...) { }
// Version 1: Concatenate two or more std::vector<> containers into one.
// Nicely simple, but buggy as the order of evaluation is undefined.
template<typename T, typename... A>
std::vector<T> concat1(std::vector<T> v1, const A&... vr) {
// Function append_to_vector() returns void, so I enclose it in (..., 1).
ignore_all((append_to_vector(v1, vr), 1)...);
// In fact, the evaluation order is right-to-left in gcc and MSVC.
return v1;
}
// Version 2:
// It works but looks ugly.
template<typename T, typename... A>
void concat2_aux(std::vector<T>& v1, const std::vector<T>& v2) {
append_to_vector(v1, v2);
}
template<typename T, typename... A>
void concat2_aux(std::vector<T>& v1, const std::vector<T>& v2, const A&... vr) {
append_to_vector(v1, v2);
concat2_aux(v1, vr...);
}
template<typename T, typename... A>
std::vector<T> concat2(std::vector<T> v1, const A&... vr) {
concat2_aux(v1, vr...);
return v1;
}
int main() {
const std::vector<int> v1 { 1, 2, 3 };
const std::vector<int> v2 { 4 };
const std::vector<int> v3 { 5, 6 };
for (int i : concat1(v1, v2, v3)) std::cerr << " " << i;
std::cerr << "\n"; // gcc output is: 1 2 3 5 6 4
for (int i : concat2(v1, v2, v3)) std::cerr << " " << i;
std::cerr << "\n"; // gcc output is: 1 2 3 4 5 6
}
【问题讨论】:
-
concat2() 对我来说看起来不错。恕我直言,拥有 2 个重载函数来处理单独的案例并不难看;它反映了在 Haskell 等函数式语言中为递归函数声明模式匹配案例的方式。也很容易理解。
标签: c++ templates c++11 variadic-templates