-1

I have the following struct:

template<typename T>
struct S {
std::unique_ptr<T> ptr;

};

S<std::string>* s = new S<std::string>();

s->any_method();

How to override operator-> to any_method was called on ptr. To be more precise, I would like to:

The expression s->any_method() "would be translated to" s->ptr->any_method().

melpomene
  • 84,125
  • 8
  • 85
  • 148
user10121051
  • 137
  • 5
  • 1
    First your code is wrong, S is template type, then you can't use it that way. Second, there is plenty of such example over the web. Look for c++ operator-> overloading. – Jean-Baptiste Yunès Sep 12 '18 at 05:33

2 Answers2

2

First of all,

S* s = new S();

is not right. S is a class template, not a class. You need a template parameter to instantiate an object, such as:

S<int>* s = new S<int>();

Assuming that is fixed first ...

You cannot use s->any_method() when s is a pointer.

You can use s->any_method() when s is object or a reference to an object, if you overload operator->.

Here's a minimal example.

#include <memory>

template<typename T>
struct S {
   std::unique_ptr<T> ptr;
   T* operator->() { return ptr.get(); }
};

struct foo { void any_method() {} };

int main()
{
   S<foo> s;
   s->any_method();
}
R Sahu
  • 204,454
  • 14
  • 159
  • 270
0

Simply return a pointer.

template<typename T> struct S {
    S(T &&t): ptr(std::make_unique<T>(std::move(t))) {}
    S(T const &t): ptr(std::make_unique<T>(t)) {}

    T *operator->() { return ptr.get(); }
    std::add_const_t<T> const *operator->() { return ptr.get(); }
private:
    std::unique_ptr<T> ptr;
};
bipll
  • 11,747
  • 1
  • 18
  • 32