Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Qt C++ lambda expression does not deduce return type

Tags:

c++

lambda

qt

I have a lambda expression, which wraps a member function from another class so I can use it in other classes like it's their own member.

auto fun = [this] (const QString& imageName) -> QImage {
    typedef QImage result_type;
    return _mapper(imageName);
};

The _mapper functor is from another class and returns a QImage.

Now my problem is that either the compiler or the Qt function, which I'm using it in, doesn't like this and can't deduce the result type.

QtConcurrent/qtconcurrentmapkernel.h:124: error: no type named ‘result_type’ in ‘struct *mystruct_ptr*::<lambda(const class QString&)>’
     IntermediateResults<typename MapFunctor::result_type> results;
                                                           ^

But a more traditional std::bind works:

auto fun_binded = std::bind(&Mapper::operator(), &_mapper, std::placeholders::_1);

So the question: What's the problem with the lambda?

Maybe I should mention the context in which I am using it:

QtConcurrent::mappedReduced<QList<QImage>>(*image_container*, fun, fun_reduce))

fun_reduce was done similarly, except it has a void function.

like image 449
Tibor Czimbor Avatar asked Dec 04 '25 15:12

Tibor Czimbor


1 Answers

The issue is that a lambda does not define the member type result_type that the library uses in typename MapFunctor::result_type but std::function does.

The library expects result_type to be defined.

So either stick to std::bind, or wrap your lambda in an std::function:

// This will convert the lambda to an std::function
std::function<QImage(const QString&)> fun =
     [this](const QString& imageName) { return _mapper(imageName);};

Or write a custom struct with this type defined.

struct MyFunctor
{
    using result_type = QImage;

    // Here you must store a pointer or a ref to the "owner" (this)

    QImage operator()(const QString& imageName) {
        return owner->mapper(imageName);
    }
};
like image 116
Guillaume Gris Avatar answered Dec 07 '25 05:12

Guillaume Gris



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!