使用点运算符触发强制转换运算符 [英] Trigger cast operator on use of the dot operator

查看:118
本文介绍了使用点运算符触发强制转换运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类似这样的课程:

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.

我想知道是否有一种无需这样做的方法((point)myPoint) 。X。我知道我可以重载->运算符,但我不希望这样做,因为它应该假装为非指针。

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.

推荐答案

您可以使用-> 而不是来实现相似

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

然后:

struct point { float x; float y; }

//...

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

这篇关于使用点运算符触发强制转换运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆