lundi 1 mars 2021

Forwarding additional arguments via lambda function

Here is the minimal reproducible code,

#include <iostream>
#include <string>

void bar(std::string s, int x){        
    std::cout <<std::endl<< __FUNCTION__<<":"<<s<<" "<<x;
}

using f_ptr = void(*)(std::string);


void foo(f_ptr ptr){        
    ptr("Hello world");
}


template<typename T> void fun(T f){
        static int x;
        std::cout <<std::endl<<x++<<std::endl;
        f("Hello World");
}

int main()
{    
    //case:1
    f_ptr ptr1 = [](std::string s){bar(s,10);}; 
   // foo(ptr1);
    
    //case:2
    static int x =10;
    f_ptr ptr2 = [x](std::string s){bar(s,x);}; 
    //foo(ptr2); 
    
    
    //case:3
    int y =10;
    f_ptr ptr3 = [y](std::string s){bar(s,y);}; /* error*/
    foo(ptr3); 
    
    //case:4
    int z = 12;
    fun([z](std::string s){bar(s,z);});
    
    return 0;
}

Error:

main.cpp:25:50: error: cannot convert ‘main()::’ to ‘f_ptr {aka void (*)(std::basic_string)}’ in initialization
         f_ptr ptr3 = [y](std::string s){bar(s,y);}; /* error*/

My questions are,

  1. Is there any way to forwards additional arguments like case:3 via lambda?
  2. What conversion is causing error in case:3?
  3. In case:4,typename T is deduced to what?

Aucun commentaire:

Enregistrer un commentaire