Nick Mack
Nick Mack

Reputation: 75

The "no operator" operator, what is it?

What operator overload would allow me to do this? Is there a "no operator" operator? I understand that to get the value I must do some kind of call(), but I'd like to know if it's possible to clean it up.

template<typename T>
class Stuff{
private:
  T stuff{};
public:
  T& operator () (){
  return stuff;
  }
  T& operator = (const T& val){
  stuff = val;
  return stuff;
  }
};

int main()
{
  int myInt = 0;
  Stuff<int> stuff;
  stuff = myInt;
  myInt = stuff(); // <- works
  myInt = stuff; // <- doesn't, is there a way to do it ?
}

Upvotes: 0

Views: 229

Answers (1)

Bathsheba
Bathsheba

Reputation: 234785

Yes there is a way: build a user-defined conversion function in Stuff:

operator T() const
{
    std::cout << "I'm here";
    return 0;     
}

Because myInt is a T type, this function will be called in the assignment myInt = stuff.

Upvotes: 2

Related Questions