7

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?

LogicStuff
  • 19,397
  • 6
  • 54
  • 74
Jobin
  • 6,506
  • 5
  • 24
  • 26

1 Answers1

13

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.

Community
  • 1
  • 1
LogicStuff
  • 19,397
  • 6
  • 54
  • 74