Trigger cast operator on use of the dot operator

2019-07-23 08:01发布

问题:

I have a class something like this:

template<typename T>
class wrapper
{
public:
    operator const T & () const
    {
        return value;
    }
private:
    T value;
};

I then use it with a struct like this:

struct point { float x; float y; };

//...

wrapper<point> myPoint;
std::cout << myPoint.x;// error: no member x or whatever.

I'm wondering if there's a way to allow this without having to do ((point)myPoint).x. I know that I can overload the -> operator but I'd prefer not to since its supposed to "pretend" to be a non-pointer.

回答1:

You can achieve something similar with -> instead of .:

template<typename T>
class wrapper
{
public:
    operator const T & () const // will this still be needed now?
    {
        return value;
    }

    T* operator->() { return &value; }
    T const* operator->() const { return &value; }

private:
    T value;
};

And then:

struct point { float x; float y; }

//...

wrapper<point> myPoint; // this needs to be initialised!
std::cout << myPoint->x;


回答2:

You cannot make your wrapper class pretend to be a real class the way you described. The main reason is that member selection (.) operator cannot be overloaded.