2
#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?

2
  • what is the error you are getting. It is running fine here: ideone.com/zI3iL Commented Apr 13, 2011 at 9:29
  • its no error, Im just wondering when using a lambda with a template, is decltype the only way to tell the lambda the type of the template, is the the correct way to code? Commented Apr 13, 2011 at 9:31

1 Answer 1

2

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;
Sign up to request clarification or add additional context in comments.

2 Comments

I much prefer the way the OP did it.
@AndresJaanTack : Fair statement – given the year and a half since I answered this originally, my level of comfort with C++11 idioms has evolved enough that at this point I would probably use the OP's approach as well. :-] That said, I do still have some lingering concerns with the OP's approach in regards to iterators that return proxy objects (e.g. std::vector<bool>::iterator), though I don't know if those concerns are truly well-founded.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.