使用点运算符时触发转换运算符

时间:2012-08-03 16:19:32

标签: c++ casting implicit-conversion implicit-cast

我的课程类似:

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

然后我将它与这样的结构一起使用:

struct point { float x; float y; };

//...

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

我想知道是否有办法允许这样做而不必((指向)myPoint).x。我知道我可以重载 - &gt;运算符,但我不愿意,因为它应该“假装”成为非指针。

2 个答案:

答案 0 :(得分:3)

您可以使用->代替.来实现类似的内容:

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;
};

然后:

struct point { float x; float y; }

//...

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

答案 1 :(得分:1)

你不能像你描述的那样让你的包装类假装成真正的类。主要原因是成员选择(。)运算符不能重载。