【发布时间】:2012-11-10 21:02:46
【问题描述】:
我在 scala 的平面地图上实现了一个函数,我想知道我是否可以在 lambda 中访问 lambda 的返回类型以避免在使用时重复它
/**
* Inspired on scala's flat map, provide a @param func which output will be flattened in the output
* sequence, which is the return type of @param func
*/
template <typename IN, typename F>
auto flat_mapf(const IN& input, F func)
-> decltype(func(std::declval<typename IN::value_type>()))
{
decltype(func(std::declval<typename IN::value_type>())) output;
auto outit = std::back_inserter(output);
for (auto i = input.begin(); i != input.end(); ++i)
{
decltype(func(std::declval<typename IN::value_type>())) interm = func(*i);
std::move(interm.begin(), interm.end(), outit);
}
return output;
}
// usage example, I would like to avoid repeating vector<size_t> type two times:
auto vo = flat_mapf(vi, [](const size_t& x) -> vector<size_t> {
vector<size_t> res;
for (size_t i = 0; i < x; ++i)
res.push_back(x);
return res;
});
【问题讨论】:
-
嗯?所以你想避免
vector<size_t>行中的vector<size_t> res;? -
我可能错了,但我认为 lambdas 的返回类型是可选的。
-
哇。你有什么错误,你必须重复两次
vector<size_t>,而不是flat_mapf中的巨大decltype?备注:auto interm = func(*i);. -
@Xeo - 库作者更关心
flat_mapf的用户 的体验而不是其内部实现的样子,这是可以理解的。除了实现之外,还有更多的用途(尤其是在这里,因为flat_mapf是一元的“绑定”操作)。 -
@Daniel:除了 lambda 不是库的一部分,所以库作者无能为力。