Inside an algorithm, I want to create a lambda that accepts an element by reference-to-const:
template<typename Iterator>
void solve_world_hunger(Iterator it)
{
auto lambda = [](const decltype(*it)& x){
auto y = x; // this should work
x = x; // this should fail
};
}
The compiler does not like this code:
Error: »const«-qualifier cannot be applied to »int&« (translated manually from German)
Then I realized that decltype(*it) is already a reference, and of course those cannot be made const. If I remove the const, the code compiles, but I want x = x to fail.
Let us trust the programmer (which is me) for a minute and get rid of the const and the explicit &, which gets dropped due to reference collapsing rules, anyways. But wait, is decltype(*it) actually guaranteed to be a reference, or should I add the explicit & to be on the safe side?
If we do not trust the programmer, I can think two solutions to solve the problem:
(const typename std::remove_reference<decltype(*it)>::type& x)
(const typename std::iterator_traits<Iterator>::value_type& x)
You can decide for yourself which one is uglier. Ideally, I would want a solution that does not involve any template meta-programming, because my target audience has never heard of that before. So:
Question 1: Is decltype(*it)& always the same as decltype(*it)?
Question 2: How can I pass an element by reference-to-const without template meta-programming?
Question 1: no, the requirement on InputIterator is merely that
*itis convertible to T (table 72, in “Iterator requirements”).So
decltype(*it)could for example beconst char&for an iterator whosevalue_typeisint. Or it could beint. Ordouble.Using
iterator_traitsis not equivalent to usingdecltype, decide which you want.For the same reason,
auto value = *it;does not necessarily give you a variable with the value type of the iterator.Question 2: might depend what you mean by template meta-programming.
If using a traits type is TMP, then there’s no way of specifying “const reference to the value type of an iterator” without TMP, because
iterator_traitsis the only means to access the value type of an arbitrary iterator.If you want to const-ify the
decltypethen how about this?You might have to capture
ret_typein order to use its type, I can’t easily check at the moment.Unfortunately it dereferences the iterator an extra time. You could probably write some clever code to avoid that, but the clever code would end up being an alternative version of
remove_reference, hence TMP.