It is possible to get functionality similar to .NET's LINQ in C++?
It is possible to get functionality similar to .NET's LINQ in C++? Would this require language extensions or could it be done using some very clever macros? Or even through a to开发者_StackOverflow中文版ol like Qt's moc (meta-object compiler)? Are there any existing LINQ implementations for C++ and if so, what are they?
Check CLinq (here and here) or Linq++ (here). Also try p-stade (here); however, it uses the STL and it doesn't have the same interface as LINQ, but it's pretty complete.
With this Linq library for C++11, you can do list comprehension using linq-like syntax:
std::vector<int> numbers = { 1, 2, 3, 4 };
auto r = LINQ(from(x, numbers) where(x > 2) select(x * x));
for (auto x : r) printf("%i\n", x);
It uses the preprocessor to parse out the from
, where
, and select
clauses, and converts it to the equivalent of this using Boost.Range adaptors:
auto r = numbers
| boost::adaptors::filtered([](int x) { return x > 2; })
| boost::adaptors::transformed([](int x) { return x * x; });
It is possible to get functionality similar to .NET's LINQ in C++? Would this require language extensions or could it be done using some very clever macros?
C++ macros aren't powerful enough to implement something as complex as LINQ.
To implement LINQ-like system in the form of library, the language needs:
- Good embedded-DSL capabilities.
- Lazy evaluation
- Persistent collections
- Lambda expressions
Embedded DSLs in C++ look very ugly thanks to the rigorous syntax and semantics of the language (for example, look at Boost.Spirit and then look at an equivalent library from a DSL-friendly language like Haskell). You can get lazy evaluation via boost::phoenix
. There is no persistent collections library available for C++ (apart from FC++, which is pretty incomplete). Lambda Expressions are coming to C++ in the next standard of the language.
Even if someday someone manages to create a LINQ-like system for C++ using above-mentioned ingredients, that system won't be as good as LINQ in .NET. So yes, it is possible, but not very practical. :)
Or even through a tool like Qt's moc (meta-object compiler)?
This is very much possible. But then it won't still really be C++, will it? ;)
Are there any existing LINQ implementations for C++ and if so, what are they?
A few attempts have been made in this direction (as pointed out by other gentleman here). None of them comes close to the "real" LINQ, but they're still worth having a look at. :)
EDIT:
Apparently I was wrong about the "practical" bit. Look at the p-stade link in Yassin's answer, which is a great example of what can be achieved with clever use of powerful C++ abstractions. :-)
精彩评论