模板和lambda c++ 0x的问题

Problem with template and lambda C++0x

本文关键字:0x 问题 c++ lambda      更新时间:2023-10-16
#include <iostream>
#include <algorithm>
#include <array>
using namespace std;
template<class T>
void func(T beg, T end)
{
    typedef decltype(*beg) type;
    std::for_each(beg, end, [](type t) { cout << t << endl; });
}
int main()
{
    std::array<int, 4> arr = { 1,2,3,4 };
    func(arr.begin(), arr.end());
    return 0;
} 

decltype的方式去告诉lambda表达式什么类型将使用?

这可能是可以接受的,但是由于您的代码似乎只期望迭代器,我认为以下格式更合适:

typedef typename std::iterator_traits<T>::value_type type;

或者更好(考虑到你如何使用它):

typedef typename std::add_reference<
    typename std::add_const<
        typename std::iterator_traits<T>::value_type
    >::type
>::type type;