Can lambda functions be templated?

前端 未结 11 2541
你的背包
你的背包 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 02:02

    C++11 lambdas can't be templated as stated in other answers but decltype() seems to help when using a lambda within a templated class or function.

    #include 
    #include 
    
    using namespace std;
    
    template
    void boring_template_fn(T t){
        auto identity = [](decltype(t) t){ return t;};
        std::cout << identity(t) << std::endl;
    }
    
    int main(int argc, char *argv[]) {
        std::string s("My string");
        boring_template_fn(s);
        boring_template_fn(1024);
        boring_template_fn(true);
    }
    

    Prints:

    My string
    1024
    1
    

    I've found this technique is helps when working with templated code but realize it still means lambdas themselves can't be templated.

提交回复
热议问题