DarthRubik
DarthRubik

Reputation: 3975

Automatic type conversion

Suppose I have a class like so (Note that this is modeled after the Method Wrapper by Stroustrup:

template<class T>
struct Wrapper
{

  private:

  //This class is implicitly convertable to T&
  struct TempRef 
  { 
     operator T&(); 
     T& operator()(); 
     ~TempRef();   //Executes clean up code
  };
  struct TempPtr 
  { 
    T* operator T->(); 
    ~TempPtr();  //Executes clean up code
  };

  public:
  TempRef operator*();
  TempPtr operator->();

};

The goal for this class is for it to act like a pointer to T:

And it works in some cases:

Wrapper<thing> var;
var->foo();

The problem comes when I want to use it as wrapper for an integral type:

Wrapper<int> var;
//*var = 12;  //Oops!! Does not work (no automatic conversion)
((int&)(*var)) = 12; //Works but the syntax is a pain
(*var)() = 12;  //Good but still could be better

So the question is this:

Is there any way to make the syntax for using Wrapper as a wrapper for an integral type the same as a pointer to an integral type, or is that just impossible at the moment?

Upvotes: 1

Views: 72

Answers (1)

1201ProgramAlarm
1201ProgramAlarm

Reputation: 32732

You need to define an assignment operator in Wrapper. Something like

Wrapper<T> &operator=(const T &v) {
    /*something to get the T& returned by TempRef::operator T&*/ = v;
    return *this;
}

This would then be invoked by var = 12;.

Upvotes: 1

Related Questions