0

I'm trying to write a template class that overrides some functions of a given class. A simple example would be best to describe what I'm trying to do...

#include <iostream>
using namespace std;

class box{
public:
    void print(){ cout << "Good!"; }
};

template <class T>
class shadow{
    T obj;
public:
    T& operator. (void) { return obj; }
};

int main(void){
    shadow<box> t;
    t.print();
}

Check in main what I want to do. I want to simulate the call to one of box' methods through the template class. It seems operator '.' can't be overloaded. The closest I've managed to get to this, is by overloading the operator ().

T& operator() (void) { return obj; }

and calling t().print() in main. Could you propose a better way to do what I'm trying to? Thanks in advance.

ps: I really have to do it this way, I don't want to use inheritance.

5
  • What do you want to achieve effectively? Sounds like a XY problem for me. Commented Jun 14, 2014 at 8:54
  • 2
    operator . cannot be overloaded, but you can overload operator *, then call t->print(). Commented Jun 14, 2014 at 8:55
  • 2
    You could overload operator* of shadow and use the t->print() syntax like smart pointers do. Commented Jun 14, 2014 at 8:55
  • @Csq I think you mean (*t).print(). Commented Jun 14, 2014 at 9:15
  • @juanchopanza yes, and operator-> is needed for t->print(), like in your answer. Thanks for the correction. Commented Jun 14, 2014 at 9:24

1 Answer 1

6

One option would be to overload T* operator-> and/or T& operator*():

template <class T>
class shadow{
    T obj;
public:
    T* operator->() { return &obj; }
    const T* operator->() const { return &obj; }
};

where I have omitted T& operator*() for brevity, although it makes sense to have both. Then use it like this:

int main()
{
    shadow<box> t;
    t->print();
}

Alternatively, provide a conversion operator operator T&();, and pass t to functions with parameters of the template argument type:

template <class T>
class shadow{
    T obj;
public:
    operator T&() { return obj; }
    operator const T&() const { return obj; }

void foo(const box& b)
{
  b.print(); // Note: you need to make box::print() a const member function
}

int main()
{
    shadow<box> t;
    foo(t);
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, I like the 1st option more... Though not being what I really had in mind, it's not bad...

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.