C ++在struct / class包装器中重载auto运算符

问题描述 投票:3回答:1

想象一下,你有一个带有两个setter和getter的简单2D Point对象。

template <typename T>
class Point
{
public:
    Point(T x, T y);

    T getX() const;
    T getY() const;

    void setX(T x);
    void setY(T y);

private:
    T _x;
    T _y;
};

但是我希望在更像“类似脚本”的语法中使用这个类。就像是 :

auto point = Point<double>(10, 10);
point.x = 20;
point.y = point.x + 10;

你会说,只需使用带有公共变量的结构:

template <typename T>
struct Point
{
    T x;
    T y;
};

是的,但我想保留参数的隐私,并用一些方法扩展类。所以另一个想法是创建一个包装器助手,为setter / getters添加运算符别名:

template <typename T, typename Get,  Get(T::*Getter)() const,
                      typename Set, void(T::*Setter)(Set)>
struct ReadWrite
{
    ReadWrite(T& ptr) : ptr(ptr) {}

    inline void operator= (Set const& rhs)
    {
        (ptr.*Setter)(rhs);
    }

    inline Get operator()()
    {
        return (ptr.*Getter)();
    }

private:
    T& ptr;
};

好的,我只是修改我的Point类来完成工作:

template <typename T>
class Point
{
public:
    Point(T x, T y);

    T getX() const;
    T getY() const;

    void setX(T x);
    void setY(T y);

private:
    T _x;
    T _y;

public:
     ReadWrite<Point<T>, T, &Point<T>::getX, T, &Point<T>::setX> x;
     ReadWrite<Point<T>, T, &Point<T>::getY, T, &Point<T>::setY> y;
};

通过添加一些算术运算符(+ - * /),我可以像这样使用它:

auto point = Point<double>(10, 10);
point.x = 20;
point.y = point.x + 10;

在这里,point.x可以在运算符重载的情况下使用:

template <typename T, typename V> inline T operator+(ReadWrite<T> const& lhs, V const& rhs) { return lhs() + rhs; }
template <typename T, typename V> inline T operator-(ReadWrite<T> const& lhs, V const& rhs) { return lhs() - rhs; }
template <typename T, typename V> inline T operator*(ReadWrite<T> const& lhs, V const& rhs) { return lhs() * rhs; }
template <typename T, typename V> inline T operator/(ReadWrite<T> const& lhs, V const& rhs) { return lhs() / rhs; }

如果我想使用这种语法,但在point.x getter上没有括号:

auto point = Point<double>(10, 10);
auto x = point.x();

我扩展了ReadWrite助手:

template <typename T, typename Get,  Get(T::*Getter)() const,
                      typename Set, void(T::*Setter)(Set)>
struct ReadWrite
{
    ReadWrite(T& ptr) : ptr(ptr) {}

    inline void operator= (Set const& rhs)
    {
        (ptr.*Setter)(rhs);
    }

    inline Get operator()()
    {
        return (ptr.*Getter)();
    }

    inline operator auto() -> Get
    {
        return operator()();
    }

private:
    T& ptr;
}; 

现在没有括号:

double x = point.x; // OK, x is my x value (Point).
auto x = point.x;   // Wrong, x is my ReadWrite<T> struct.

auto运算符的重载有什么问题?

非常感谢您的回答。

c++ operator-overloading wrapper template-meta-programming auto
1个回答
7
投票

你的班级没有任何问题。问题是如何自动推断类型。你必须记住关于auto的事情是它基本上遵循模板参数推导的规则,主要的是没有隐式转换。这意味着

auto x = point.x;

你说编译器,给我一个名为x的变量,它具有初始化表达式的类型。在这种情况下,point.xReadWrite<Point<T>, T, &Point<T>::getX, T, &Point<T>::setX>所以这是x得到的类型。更改它的唯一方法是更改​​初始化表达式返回的内容。

不幸的是我不确定你怎么能这样做。代理对象在自动类型扣除方面效果不佳,因为我们选择了它们的类型,而不是它们模仿的类型。

© www.soinside.com 2019 - 2024. All rights reserved.