C ++ lambda模糊调用 [英] C++ lambda ambiguous call

查看:36
本文介绍了C ++ lambda模糊调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图每个都有两个Pixel函数.一个返回图像,另一个不返回任何图像.即使指定了lambda的返回类型,我也仍然对eachPixel的调用不明确".

I am trying to have two eachPixel functions. One returns an image, and the other returns nothing. I'm getting "call to eachPixel is ambiguous" even though I am specifying the return type of the lambda.

如何解决歧义?

// this one does not return an image
void eachPixel(const QImage &image, const std::function <void (uint)>& pixelFunc, const QRect &bounds=QRect()) {
...

    for (int y=region.y(); y<=region.bottom(); y++) {
        for (int x=region.x(); x<=region.right(); x++) {
            pixelFunc(image.pixel(x,y));
        }
    }
}

// This one returns an image
QImage eachPixel(const QImage &image, const std::function <uint (uint)>& pixelFunc, const QRect &bounds=QRect()) {
...

    QImage out(image.size(), image.format());
    for (int y=region.y(); y<=region.bottom(); y++) {
        for (int x=region.x(); x<=region.right(); x++) {
            out.setPixel(x,y, pixelFunc(image.pixel(x,y)));
        }
    }
    return out;
}

void test_pixelFunc() {
    QImage image(300,200, QImage::Format_ARGB32);
    image.fill(Qt::blue);

    QImage out = eachPixel(image, [] (uint p) -> uint { //uint specified!!
        return qRgb(qRed(p), qBlue(p), qGreen(p)); // swap green and blue channels
    }, QRect (0,0, 300, 200));
    out.save("test_pixelfunc.png");


    int accumulator=0;
    eachPixel(image, [&accumulator](uint p) -> void { // void specified!
        accumulator++;
    }, QRect (0,0, 300, 200));
    qDebug() << "accumulator" << accumulator;

};

推荐答案

您可以在传入的函数的返回类型上使用模板和SFINAE.

You can use templates and SFINAE on the return type of the function you pass in.

#include <iostream>
#include <functional>

template <typename T, std::enable_if_t<std::is_same_v<void, decltype(std::declval<T>()(1))>, int> = 0>
void foo (T f) {
    // std::function<void(int)> func = f;
    // if you really need a std::function
    f(1);
}

template <typename T, std::enable_if_t<std::is_same_v<int, decltype(std::declval<T>()(1))>, int> = 0>
int foo (T f) {
    return f(1);
}

int main() {
    foo([](int x) { std::cout << "void " << x << '\n'; });

    foo([](int x) { std::cout << "int\n"; return x; });
}

对于c ++ 11,您可以直接使用std::is_samestd::enable_if.

For c++11 you can use std::is_same and std::enable_if directly.

template <typename T, typename std::enable_if<std::is_same<void, decltype(std::declval<T>()(1))>::value, int>::type = 0>
void foo (T f) {
    f(1);
}

template <typename T, typename std::enable_if<std::is_same<int, decltype(std::declval<T>()(1))>::value, int>::type = 0>
int foo (T f) {
    return f(1);
}

这篇关于C ++ lambda模糊调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆