我希望有一个模板函数,接受一个vector <T> v
和一个函数op,将T
映射到vector <U>
,并希望连接应用于每个向量元素的f
的结果,以返回vector <U>
= [ op(v[0])中的元素,op(v[1])中的元素... ]。
我发现一种有效的解决方案是在函数中添加一个例子,以允许进行模板推断:
template <typename Container>
Container& concat(Container& c1, Container const& c2) {
c1.insert(end(c1), begin(c2), end(c2));
return c1;
}
template <typename Container, typename UnaryOperation, typename U>
inline auto to_vec_from_vectors(Container& c, UnaryOperation&& op, U& ex)
-> std::vector<U> {
std::vector<U> v;
for (auto& e : c) {
std::vector<U> opv = op(e);
concat(v, opv);
}
return v;
}
但是我希望只使用这两个参数就能达到相同的效果。
我的尝试[用decltype(*std::begin(op(*std::begin(c))))
替换U
]:
template <typename Container, typename UnaryOperation, typename U>
inline auto to_vec_from_vectors(Container& c, UnaryOperation&& op, U& ex)
-> std::vector<decltype(*std::begin(op(*std::begin(c))))> {
std::vector<decltype(*std::begin(op(*std::begin(c))))> v;
for (auto& e : c) {
std::vector<decltype(*std::begin(op(*std::begin(c))))> opv = op(e);
concat(v, opv);
}
return v;
}
很遗憾,这段代码没有编译成功。如果操作对象是复杂方法,我也担心会浪费时间。
这就是输出结果:
error: conversion from ‘std::vector<U>’ to non-scalar type ‘std::vector<const U&, std::allocator<const U&> >’ requested
error: forming pointer to reference type ‘const U&
看起来与“const”有关。
如何纠正这个变体?是否有更好的替代方案?
decltype(...)
给出的是const U&
,而不是U
。因此编译器报错。 - Max LanghofU
和ex
? - HoltU
的情况,您可能希望在连接时移动而不仅仅是复制,例如v.insert(end(v), std::make_move_iterator(begin(opv)), std::make_move_iterator(end(opv)));
。或者在调用concat
时重载concat
和std::move(opv)
。 - Holt