Re: "no matching function for call to 'begin(int&)'"
On 10/1/2013 4:26 PM, Stefan Ram wrote:
Victor Bazarov <v.bazarov@comcast.invalid> writes:
On 10/1/2013 4:10 PM, Stefan Ram wrote:
#include <iostream>
#include <ostream>
int begin( int & ){ return 1; }
int end( int & e ){ return e; }
int main(){ for( int i : 5 )::std::cout << i << '\n'; }
Error: no matching function for call to 'begin(int&)'
A reference to non-const int (the argument to 'begin' and 'end') cannot
be bound to a temporary object (in your case the literal 5 is the
temporary). A reference to const int *can*.
Yeah, but it's *the compiler* who says that he wants
to have a function ?begin(int&)?, so I tried to give
him such a function, but he does not accept it.
You might describe another error, but this other
error should not give the above error message.
(I now believe that I will not get this to work,
because the begin and end functions are supposed
to return some pointer or iterator - so that would be
yet another error. But then, the compiler should
complain about the return type, which is not what
the above error message is about.)
I got this code to compile with VC++ 2012:
8<=====================================================
#include <iostream>
namespace std {
const int* begin( const int& i)
{
std::cout << "begin(" << i << ")";
return &i;
}
const int* end( const int& e)
{
std::cout << "end(" << e << ")";
return &e;
}
}
int main()
{
for ( int i : 5 )
{
std::cout << "inside for i=" << i << '\n';
}
}
8<=====================================================
but if you look, since both 'begin' and 'end' return the same address,
the loop does not execute even once. If you want it to run once with
the given value, you will need to make 'end' return a pointer that
follows the address of that temporary, which is tricky to say the least.
It can be done with static variables, but it's not thread-safe. You
could probably play some trick with special class, but is it worth it?
V
--
I do not respond to top-posted replies, please don't ask