我已经实现了一个受scala flat map启发的函数,我想知道我是否可以在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>
吗?从用法示例中,编译器推断出 lambda 的返回类型?这样您只需说一次类型。
关于c++ - 从 lambda 内部返回 C++11 中 lambda 的类型(平面映射函数),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13513129/