开发者

Problem with template and lambda C++0x

#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;
} 

Is decltype the way to go when telling the lambda expression what 开发者_运维问答type is going to use?


That's probably acceptable, however as your code appears to expect iterators exclusively, I think that the following would be more appropriate:

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

Or even better (given how you're using it):

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜