简体   繁体   English

C++,我怎样才能得到一个 noop lambda 类型来匹配一个空 function Z945F3FZFC5495188ADB7623

[英]C++, how I can get a noop lambda type to match a void function lambda type

The code I want to work我想要工作的代码

#include <iostream>

using namespace std;

int main()
{
    int v = 123;
    
    auto doFn = [v](){ cout << "Hello World" << v << "\n"; };
    auto noopFn = [v](){};

    for (int i = 0; i < 4; ++i)
    {
        auto fn = (i & 1) ? doFn : noopFn;
        fn();
    }

    return 0;
}

The error I get我得到的错误

main.cpp:14:27: error: operands to ?: have different types ‘main()::’ and ‘main()::’
   14 |         auto fn = (i & 1) ? doFn : noopFn;
      |                   ~~~~~~~~^~~~~~~~~~~~~~~

I found this answer but if it's a solution I don't understand how to apply it.我找到了这个答案,但如果它是一个解决方案,我不明白如何应用它。

The lambda (fast way): lambda(快速方式):

int main()
{
    int v = 123;
    
    auto doFn = [v](){ cout << "Hello World" << v << "\n"; };
    auto noopFn = [v](){};

    for (int i = 0; i < 4; ++i)
    {
        auto fn = [=] { i & 1 ? doFn() : noopFn(); };
        fn();
    }

    return 0;
}

The std::function (slow way): std::function (慢):

int main()
{
    int v = 123;
    
    auto doFn = [v](){ std::cout << "Hello World" << v << "\n"; };
    auto noopFn = [v](){};

    for (int i = 0; i < 4; ++i)
    {
        auto fn =  i & 1 ? std::function{doFn} : noopFn;
        fn();
    }

    return 0;
}

Change the lambdas the following way通过以下方式更改 lambda

auto doFn = []( const int &v){ std::cout << "Hello World" << v << "\n"; };
auto noopFn = []( const int &v){};

for (int i = 0; i < 4; ++i)
{
    auto fn = (i & 1) ? doFn : noopFn;
    fn(v);
}

As @TheDreamsWind pointed out正如@TheDreamsWind 指出的

Wrap the closures with std::function用 std::function 包裹闭包

#include <iostream>
#include <functional>

using namespace std;

int main()
{
    int v = 123;
    
    auto doFn = std::function<void()>([v](){ cout << "Hello World" << v << "\n"; });
    auto noopFn = std::function<void()>([v](){});

    for (int i = 0; i < 4; ++i)
    {
        auto fn = (i & 1) ? doFn : noopFn;
        fn();
    }

    return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM