Can lambda functions be templated?

前端 未结 11 2525
你的背包
你的背包 2020-11-28 01:44

In C++11, is there a way to template a lambda function? Or is it inherently too specific to be templated?

I understand that I can define a classic templated class/fu

11条回答
  •  自闭症患者
    2020-11-28 01:49

    Here is one solution that involves wrapping the lamba in a structure:

    template                                                    
    struct LamT                                                             
    {                                                                       
       static void Go()                                                     
       {                                                                    
          auto lam = []()                                                   
          {                                                                 
             T var;                                                         
             std::cout << "lam, type = " << typeid(var).name() << std::endl;
          };                                                                
    
          lam();                                                            
       }                                                                    
    };   
    

    To use do:

    LamT::Go();  
    LamT::Go(); 
    #This prints 
    lam, type = i
    lam, type = c
    

    The main issue with this (besides the extra typing) you cannot embed this structure definition inside another method or you get (gcc 4.9)

    error: a template declaration cannot appear at block scope
    

    I also tried doing this:

    template  using LamdaT = decltype(                          
       [](void)                                                          
       {                                                                 
           std::cout << "LambT type = " << typeid(T).name() << std::endl;  
       });
    

    With the hope that I could use it like this:

    LamdaT();      
    LamdaT();
    

    But I get the compiler error:

    error: lambda-expression in unevaluated context
    

    So this doesn't work ... but even if it did compile it would be of limited use because we would still have to put the "using LamdaT" at file scope (because it is a template) which sort of defeats the purpose of lambdas.

提交回复
热议问题