Trigger cast operator on use of the dot operator

我怕爱的太早我们不能终老 提交于 2019-12-11 04:56:03

问题


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.



来源:https://stackoverflow.com/questions/11799540/trigger-cast-operator-on-use-of-the-dot-operator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!