C++逗号运算符重载和引用向量

C++ comma operator overloading and vector of references

本文关键字:引用 向量 重载 运算符 C++      更新时间:2023-10-16

有很多关于 C++ 中逗号运算符重载的帖子(问题)。大多数答案建议不要使用逗号运算符重载。我想编写一个语法与 Matlab 语言非常相似的 c++ 库。基本对象是矩阵 MX。我希望能够让库的最终用户编写如下表达式:

MX a = b(i);// get b elements at indices i 
b(i,j)= a; // set elements of b at indices i,j.

我有一个关于如何使用代理类使setter和getter工作的想法,该代理类保存指向MX对象的指针并保存索引i,j对象。例如,b(i,j) 将创建一个代理对象 ProxMX(b,i,j)。然后我们定义一种方法将ProxMX分配给MX,反之亦然(使用运算符=),它们完成了获取和设置b元素的艰巨工作。

我需要帮助进行函数调用,例如:

(x,y,z)= ff(a,b,c) 

其中 a、b、c 是输入参数(MX 对象),x、y 、z 是输出参数。如果上述语法是不可能的,我可以考虑这样的语法:

ff((a,b,c), (x,y,z) )

我开始编写这个测试代码:

#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;


class MX {// Matrix 
public:
    MX(double va) {
        elem=va;// only one double for the moment to test the syntaxe
    }
    MX &operator ()(MX idx){ // get & set MX(i)
        return *this;//
    };
    MX &operator ()(MX idx1,MX idx2) { // get set MX(i,j)
        return *this;
    } ;
    friend ostream &operator<<(ostream &stream, MX a);
    double elem;
};
ostream &operator<<(ostream &stream, MX a)
{
  stream << a.elem ;
  return stream;
}
typedef vector<const MX > MXR;
class ArgList { // Proxy
public:
    //ArgList(const MX& a){
    //  data.push_back(a);
    //}
    ArgList() {};
    ArgList& operator , (const MX &a){
        data.push_back(a);
        return *this;
   }
   ArgList& operator =(ArgList& ins){
        for (int i=0 ;i <ins.data.size();i++)
            (this->data[i]).elem=ins.data[i].elem;
        return *this;
   };
    MXR data; 
};

ArgList operator , (const MX& a, const MX& b){
    ArgList out;    
    out.data.push_back(a);
    out.data.push_back(b);
    return out;
   }
ArgList ff(ArgList argins)
{
    int n = argins.data.size();
    MX a= argins.data[0];
    MX b= argins.data[1];
    MX x(a.elem+1.0);
    MX y(b.elem+10.0);
    MX z(a.elem+b.elem);
    return ( x, y , z);
}
void gg(ArgList argins, ArgList &argout)
{
    int n = argins.data.size();
    MX a= argins.data[0];
    MX b= argins.data[1];
    MX x(a.elem+1.0);
    MX y(b.elem+10.0);
    MX z(a.elem+b.elem);
    argout = ( x, y , z);
}
int _tmain(int argc, _TCHAR* argv[])
{
    MX a(1.0);MX b(2.0);MX c(3.0);
    MX aa = a(MX(3.0));
    aa(MX(2.0),MX(3.0))=MX(5.0);
    cout << "a=" << a << ",b=" << b << ",c=" << c << endl;
    MX x(0.0);MX y(0.0);MX z(0.0);
    cout << "x=" << x << ",y=" << y << ",z=" << z << endl;
    (x,y,z)= ff((a , b, c ));
    cout << "x=" << x << ",y=" << y << ",z=" << z << endl;
    gg((a,b,c) , (x,y,z));
    cout << "x=" << x << ",y=" << y << ",z=" << z << endl;
    return 0;
}

此代码使用 VS2010 Express :)编译和运行,没有错误。但正如预期的那样,它没有给出预期的结果,因为我需要在 ArgList 中保存对变量的引用,而不是将对象复制到 vector。我知道我们不能使用 std::vector 作为对象引用的容器。

任何帮助,以使这些表达式可写并在C ++代码中工作。谢谢。

我正在使用 C++11 来概述您的解决方案(代码也经过测试),但这在 C++03 中是可行的(例如使用 Boost.Tuple):

// Base case
template<typename Lhs, typename Rhs>
std::tuple<Lhs&, Rhs&>
operator,(Lhs& lhs, Rhs& rhs)
{
    return std::tie(lhs, rhs);
}
// General case when we already have a tuple
template<typename... Lhs, typename Rhs>
std::tuple<Lhs..., Rhs&>
operator,(std::tuple<Lhs...>&& lhs, Rhs& rhs)
{
    return std::tuple_cat(lhs, std::tie(rhs));
}

用法如下所示(假设此运算符驻留在namespace ns):

// Declaration: note how ff must return a tuple
std::tuple<X, Y, Z> ff(A, B, C);
A a = /* ... */;
B b = /* ... */;
C c = /* ... */;
X x; Y y; Z z;
using ns::operator,;
// brackets on the left-hand side are required
(x, y, z) = ff(a, b, c);

以下是随附的注意事项:

  • 如您所见,您需要一个 using 声明才能将operator,引入范围。即使类型XYZ驻留在相同的operator,范围内(以启用 ADL),std::tuple也不会。您可以执行类似 template<typename... T> struct tuple: std::tuple<T...> { using std::tuple<T...>::tuple; }; 的操作(但是在 C++03 中不那么方便)在适当的命名空间中拥有自己的元组,以便以快速而肮脏的方式拥有 ADL。然而:

  • 重载运算符必须始终对至少一个用户定义类型进行操作。因此,如果类型 XY 恰好都是 intdouble 这样的类型,那么您将获得默认operator, 。对于此类事情,通常的解决方案是要求客户端执行类似 (ref(x), ref(y), z) = ff(a, b, c); 的操作,其中 ref 将在适当的命名空间中返回一个类型(再次用于 ADL 目的)。也许这种类型可以在std::reference_wrapper(或 Boost 版本,用于 C++03)方面实现,具有与元组相同的快速和肮脏的黑客。(您需要额外的重载operator,

总而言之,当类似的事情发生时,这是很多工作(带有丑陋的解决方法)

/* declaration of ff and variable definitions the same as before */
std::tie(x, y, z) = ff(a, b, c);

或者也许

/* this skips unnecessary default constructions of x, y, z */
auto tuple = ff(a, b, c);
using std::get;
auto& x = get<0>(tuple);
auto& y = get<1>(tuple);
auto& z = get<2>(tuple);

开箱即用(即使在 C++03 中使用 Boost.Tuple)。我在这件事上的建议是(没有一点意图):保持简单,愚蠢! 并使用它。

在 C++11 中,您可以使用元组执行此操作:

std::tuple<some_type, another_type, yet_another_type> ff(...);
some_type x;
another_type y;
yet_another_type z;
std::tie(x,y,z) = ff(a,b,c);

如果您的编译器不支持此功能,则 Boost.Tuple 库非常相似,但如果没有可变参数模板的支持,可能会受到更多限制。

如果你真的想支持像(x,y,z) = ff(a,b,c);这样的语法,即使它在 Matlab 中看起来很合理,这对C++程序员来说也可能相当混乱,那么你几乎就在那里。您需要一个类似于ArgList的单独类型(可能称为类似 RefList ),它包含指针而不是值,从对结果的非const引用初始化这些指针,并具有一个赋值运算符,该运算符采用ArgList(或其他一些值集合)并通过指针分配每个元素。

您可能还想查看 Boost.Assignment,了解如何使这种运算符重载工作。这有点麻烦;特别是,不能重载仅作用于内置类型的运算符,这反而限制了该方法的实用性。就个人而言,如果可以选择 C++11,我会使用可变参数模板。

谢谢大家的反馈和反馈。这是一个使用 2 个代理的工作示例。ArgList 包含指向 MX 对象的指针,ArgCopyList 包含 MX 对象的副本。

从 matlab 用户的角度来看,c++ 语法(x,y,...)=myfunc((a,b,...))与 matlab 表达式[x,y,...]=myfunc(a,b,...)非常相似。但我的第一印象是这种函数调用根本没有效率,因为返回的值是复制的,这可以通过引用传递输出来避免。

#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
class MX {// Matrix 
public:
    MX(double va) {
        elem=va;// only one double for the moment to test the syntaxe
    }
    MX & operator = (const MX &src)
    {   elem = src.elem;
        return *this;
    }
    friend ostream &operator<<(ostream &stream, MX &a);
    double elem;
};
ostream &operator<<(ostream &stream, MX &a)
{
  stream << a.elem ;
  return stream;
}
typedef vector<MX *> MXR; // save pointers only 
class ArgCopyList { // copy the objects to a list
public :
    vector<const MX> data; 
    ArgCopyList(MX &a)
    {
        data.push_back(a);
    };
    ArgCopyList(MX &a, MX &b)
    {
        data.push_back(a);
        data.push_back(b);
    };
    ArgCopyList(MX &a, MX &b, MX &c)
    {
        data.push_back(a);
        data.push_back(b);
        data.push_back(c);
    };
    // do the same for bigger lists
};
class ArgList { // Proxy
public:
    ArgList() {};
    ArgList(const ArgList& src) 
    {
        data.clear();
        for (int i=0 ;i <src.data.size();i++)
            data.push_back(src.data[i]);
    }
    ArgList& operator , ( MX &a){
        data.push_back(&a);
        return *this;
   }
    ArgList  &operator= ( ArgList &src)
    {
        if (this == &src)
            return *this;
        data.clear();
        int n= src.data.size();
        for (int i=0 ;i <n;i++)
            data.push_back(src.data[i]);
        return *this;
    };

   ArgList& operator =( ArgCopyList& src){
        for (int i=0 ;i <data.size();i++)// TBD : must control the size of src & this->data here
            data.at(i)->elem = (src.data[i].elem);
        return *this;
   };
    MXR data; 
};

ArgList operator , (MX& a,  MX& b){
    ArgList out;    
    out.data.push_back(&a);
    out.data.push_back(&b);
    return out;
   }
// test function
ArgCopyList ff(ArgList argins)
{
    int n = argins.data.size();
    MX a= *(argins.data[0]);
    MX b= *(argins.data[1]);
    MX x(a.elem+1.0);
    MX y(b.elem+10.0);
    MX z(a.elem+b.elem);
    return ArgCopyList( x, y , z);
}

int _tmain(int argc, _TCHAR* argv[])
{
    MX a(1.0);MX b(2.0);MX c(3.0);
    cout << "a=" << a << ",b=" << b << ",c=" << c << endl;
    MX x(0.0);MX y(0.0);MX z(0.0);
    cout << "Argouts before calling (x,y,z)= ff((a,b,c)).nx=" << x << ",y=" << y << ",z=" << z << endl;
    (x,y,z)= ff((a , b, c) );
    cout << "Argouts after calling ff.nx=" << x << ",y=" << y << ",z=" << z << endl;
    return 0;
}
/* output
a=1,b=2,c=3
Argouts before calling (x,y,z)= ff((a,b,c)).
x=0,y=0,z=0
Argouts after calling ff.
x=2,y=12,z=3
*/