我正在使用类似Java 8的Stream实现进行尝试。我希望编译器能够接受以下代码片段。
但是编译器(gcc版本4.9.2)拒绝了它,并附有注释。
Stream stream;
stream
.map ([] (int x) { return 10*x; }) // error
.forEach ([] (int x) { cout << x << " ";});
但是编译器(gcc版本4.9.2)拒绝了它,并附有注释。
template argument deduction/substitution failed:
‘main(int, char**)::<lambda(int)>’ is not derived from ‘std::function<Re(int)>’
.map ([] (int x) { return 10*x; })
requires a type parameter for `map`
它能够编译(并且运行良好)使用以下技术:
.map<int> ([] (int x) { return 10*x; })
有没有希望摆脱那个 <map>
东西?
这里是精简的代码(已经声明足够)
#include <iostream>
#include <functional>
using namespace std;
template <typename Tfrom, typename Tto> class MappedStream;
template <typename T>
class Stream
{
public:
void forEach(function< void(T) > action)
{}
template <typename Re>
MappedStream<T,Re> map (function < Re(T)> mapping) {
return MappedStream<T,Re>(*this, mapping);
}
};
template <typename Tfrom, typename Tto>
class MappedStream
: public Stream<Tto>
{
public:
MappedStream(Stream<Tfrom> & source,
function <Tto(Tfrom)> mapping)
{}
};
int main(int argc, char **argv)
{
Stream<int> stream;
stream
.map<int> ([] (int x) { return 10*x; })
// XXXXX <- how to get rid of this?
.forEach ([] (int x) { cout << x << " ";});
return 0;
}
std::function
。 - Jarod42