Home > other >  C , how I can get a noop lambda type to match a void function lambda type
C , how I can get a noop lambda type to match a void function lambda type

Time:09-10

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.

CodePudding user response:

Change the lambdas the following way

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);
}

CodePudding user response:

The lambda (fast way):

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):

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;
}

CodePudding user response:

As @TheDreamsWind pointed out

Wrap the closures with 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;
}
  •  Tags:  
  • c
  • Related