Skip to content

Linq inside polymorphic function

pfultz2 edited this page Jul 30, 2012 · 3 revisions

Linq inside polymorphic function

Unfortunately, because of weakness in the type deduction of C++(hopefully there is a workaround for this soon), you can't return Linq queries from a polymorphic function. A simple example, is say we want to write a function that squares every number in a range that is positive, and we want to return this, have it all evaluated lazily with no copies.

template<class T>
auto square_pos(T&& range)
{
    return LINQ(from(x, range) where(x > 0) select(x*x));
}

This is not entirely correct C++ code, we are still missing the return type. If we try to fill it in like this, it won't work:

template<class T>
auto square_pos(T&& range) -> decltype(LINQ(from(x, range) where(x > 0) select(x*x)))
{
    return LINQ(from(x, range) where(x > 0) select(x*x));
}

This is because Linq uses lambdas, and lambdas can't appear inside of decltype. If we make are square_pos function only work for a vector<int> then we can use a lambda to deduce the return type:

auto square_pos = [](vector<int> & range)
{
    return LINQ(from(x, range) where(x > 0) select(x*x));
}

But this can severely limit the reusablility of the square_pos function, since lambdas can't be polymorphic.

Clone this wiki locally