Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Weird operator overloading, "operator T& () const noexcept { return *_ptr; }"

Tags:

c++

class

c++11

I studied that the format of operator functions is

(return value)operator[space]op(arguments){implementation}

But, In std::reference_wrapper implementation, there is an operator overloading function declared as operator T& () const noexcept { return *_ptr; }.

Is this operator different from T& operator () const noexcept { return *_ptr; } ?. If both are different, then what is the use of the first?

like image 335
Jobin Avatar asked Jul 04 '16 09:07

Jobin


People also ask

Which of these operators can't be overloaded?

Most can be overloaded. The only C operators that can't be are . and ?: (and sizeof , which is technically an operator). C++ adds a few of its own operators, most of which can be overloaded except :: and .

How do I overload operator+?

The name of an overloaded operator is operator x, where x is the operator as it appears in the following table. For example, to overload the addition operator, you define a function called operator+. Similarly, to overload the addition/assignment operator, +=, define a function called operator+=.

Which operator is overload operator?

Operator Overloading in C++ This means C++ has the ability to provide the operators with a special meaning for a data type, this ability is known as operator overloading. For example, we can overload an operator '+' in a class like String so that we can concatenate two strings by just using +.


1 Answers

operator T& () const noexcept; is a user-defined conversion function. std::reference_wrapper has it in order to give you access to the stored reference, without changing the syntax:

int x = 42;
int &a = x;
std::reference_wrapper<int> b = x;

std::cout << a << " " << b << std::endl;

Assignment is a little bit trickier.


T& operator () const noexcept; is an attempt to declare operator(), but fails to compile due to missing parameter list. The right syntax would be:

T& operator ()( ) const noexcept;
//             ^
//       parameters here

and the usage is completely different.

like image 152
LogicStuff Avatar answered Oct 05 '22 19:10

LogicStuff