C++11: 使用 lambda 创建模板类 的 对象

C++ 中 lambda 可以直接传递给模板函数如 std::sort, 但无法传给模板类如 std::map,但是,使用一点小技巧,可以使用 lambda 创建模板类的对象,省了很多麻烦的 coding。这里给出一个示例:

#include <stdio.h>
#include <map>

template<class Key, class Value, class Compare>
std::map<Key, Value, Compare> make_map(Compare comp) {
    return std::map<Key, Value, Compare>(comp);
}

int main() {
    auto m = make_map<int,int>([](int x, int y) { return x < y; });
    m[1] = 11;
    m[2] = 22;
    for (auto x : m) {
        printf("%d->%d\n", x.first, x.second);
    }
    return 0;
}                                    

make_map 可以被返回值优化掉。

posted on 2012-03-09 11:46  能发波  阅读(503)  评论(0)    收藏  举报

导航