1

I'm using some smart pointer implementation that contain the following operators :

template<class T>
class my_unique_ptr {
public:
    ...

    operator T() {
        return _t;
    }

    T *operator &() {
        return &_t;
    }

private:
    T _t;
};

I'm looking to get the original value from type T that wrapped by the pointer class.

The & operator works fine but it gives my pointer and not the value itself.

Therefore, I wish to call the T() operator (just like get() in std::unique_ptr)

I tried to use the variable directly, but it refers to it as my_unique_ptr<T> instead of T.

void func(myClass c);

int main()
{
     my_unique_ptr<myClass> x = new myClass(..);
     func(x); 
}

but I get error of unable cast from type 'my_unique_ptr' to pointer type 'myClass'

How can I call this operator ?

Irad K
  • 867
  • 6
  • 20
  • `operator->` is probably what you want – Eljay Jan 01 '20 at 22:36
  • Or `operator*`. – Paul Sanders Jan 01 '20 at 22:37
  • 3
    and `T* _t;` if it's supposed to store a pointer. – Ted Lyngmo Jan 01 '20 at 22:39
  • You would call () operator like this: `x();`. The code does not make much sense. `_t` is not a pointer and operator () return a copy by value. And since you don't show constructor or assignement, it make it a bad question since we cannot compile it and **cannot guess what you have written** since what we have is incoherent. Look at `std::unique_prt` code if you want to learn how to write a unique pointer. – Phil1970 Jan 01 '20 at 23:56

1 Answers1

1

How can I call this operator ?

When you use & on an object, that function will be called.

 my_unique_ptr<myClass> x = new myClass(..);
 auto ptr = &x;

Here, ptr will be of type myClass*. To be able use

 func(x); 

You'll have to define a conversion operator.

operator T&() {
    return _t;
}
R Sahu
  • 204,454
  • 14
  • 159
  • 270
  • so `operator T()` is a conversion operator as well (less efficient one). but how do I call this operator. Perhaps you can add to your example code ? – Irad K Jan 01 '20 at 22:44
  • @IradK, The function will be called implicitly when a conversion from `my_unique_ptr` to `T&` is required. To explicitly call it, you may use `x.operator myClass&();` – R Sahu Jan 01 '20 at 22:49
  • I just wonder why I got the casting error in my example If I already had this operator and according to `func` signature, it need `myClass` and not `my_unique_ptr` – Irad K Jan 01 '20 at 22:53