2

i have a class with a overladed operators.

class sout { public: template<typename T> friend inline sout& operator&(sout&, T&); friend inline sout& operator&(sout&, std::string&); }; 

now if i use the templated operator& inside the the sting.operator& i get an error:

code:

sout& operator&(sout& s, std::string& str) { uint16_t ts = static_cast<uint16_t>(str.size()); // this is ok s & ts; // is also ok s & static_cast<uint16_t>(str.size()); // but this is wrong // ... return s; } 

error:

Error:C2679: binary '&' : no operator found which takes a right-hand operand of type 'uint16_t' (or there is no acceptable conversion) could be 'sout &operator &<uint16_t>(sout &,T &)' with [ T=uint16_t ] or 'sout &operator &(sout &,std::string &)' while trying to match the argument list '(sout, uint16_t)' 

than i tried to use the explicite operator& template-type by:

operator&<uint16_t>(s, ts); // this also ig ok 

but if i combine it, i again a error:

operator&<uint16_t>(s, static_cast<uint16_t>(str.size()) 

error:

'operator &' : cannot convert parameter 2 from 'uint16_t' to 'uint16_t &' 

i also tried reinterpret_cast.

i know operator& is expecting a reference to uint16_t and the size() function is returning a size_t (int) not a reference. is it possible to do that in one line?

1
  • maybe use const reference Commented Apr 25, 2013 at 15:57

1 Answer 1

7

The problem is that the value returned by size() is a temporary, and temporaries are rvalues; however, your function accepts an lvalue reference. The following snippet clarifies the problem:

int foo() { return 42; } void bar(int& i) { i++; } // Parameter is an lvalue reference to non-const int main() { bar(foo()); // ERROR! Passing an rvalue to bar() bar(1729); // ERROR! Passing an rvalue to bar() int i = 42; bar(i); // OK! Passing an lvalue to bar() } 

lvalue references cannot bind to rvalues, unless they are references to const.

template<typename T> friend inline sout& operator&(sout&, T const&); // ^^^^^ 

If your operator& is supposed to modify the right hand argument, so that the reference cannot be a reference to const, in C++11 you may use rvalue references (this will allow to bind to lvalues as well due to C++11's reference collapsing rules):

template<typename T> friend inline sout& operator&(sout&, T&&); // ^^^ 
Sign up to request clarification or add additional context in comments.

1 Comment

@itwasntpete: Don't worry, that happens ;)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.