Can lambda functions be templated?

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

    I've been playing with the latest clang version 5.0.1 compiling with the -std=c++17 flag and there is now some nice support for auto type parameters for lambdas:

    #include 
    #include 
    #include 
    
    int main() {
        auto slice = [](auto input, int beg, int end) {
            using T = decltype(input);
            const auto size = input.size();
            if (beg > size || end > size || beg < 0 || end < 0) {
                throw std::out_of_range("beg/end must be between [0, input.size())");
            }
            if (beg > end) {
                throw std::invalid_argument("beg must be less than end");
            }
            return T(input.begin() + beg, input.begin() + end);
        };
        auto v = std::vector { 1,2,3,4,5 };
        for (auto e : slice(v, 1, 4)) {
            std::cout << e << " ";
        }
        std::cout << std::endl;
    }
    

提交回复
热议问题