运算符逗号重载

Operator comma overloading

本文关键字:重载 运算符      更新时间:2023-10-16

我正在尝试了解有关运算符重载如何工作的更多信息。

我知道重载逗号运算符可能不是最好的主意,但这仅用于教学目的。

我希望以下代码使用我的重载运算符(我使用了括号,因为我知道逗号运算符的优先级最低)来构造包含 (1,2) 的向量,然后调用向量的赋值运算符。

但是,我收到一个错误:

no known conversion from argument 1 from 'int' to 'const std::vector<int>&'

我不明白为什么会这样。 (1,2)应该构造一个向量,所以它不应该试图从int转换为vector<int>

#include <vector>
#include <utility>
using std::vector;
using std::move;
template <typename T>
vector<T> operator,(const T& v1, const T& v2)
{
    vector<T> v;
    v.push_back(v1);
    v.push_back(v2);
    return move(v);
}
int main()
{
    vector<int> a;
    a = (1,2);
    return 0;
}

已经有一个应用于整数的逗号运算符的内置定义。您的模板甚至不在重载解析运行中,因为除非至少有一个参数是用户定义类型,否则无法重载运算符。

你可以做这样的事情:

template<typename T>
struct vector_maker
{
    std::vector<T> vec;
    vector_maker& operator,(T const& rhs) {
        vec.push_back(rhs);
        return *this;
    }
    std::vector<T> finalize() {
        return std::move(vec);
    }
};
int main() {
    auto a = (vector_maker<int>(),1,2,3,4,5).finalize();
}

或者看看Boost.Assign,它允许这样的结构:

std::vector<int> a;
a += 1,2,3,4,5,6,7,8;

值右侧的表达式被简单地计算为(1,2)并退化为(2)2,这是一个int

然后评估分配。左侧为vector<int>型。您正在尝试将2int)分配给avector<int>),并且由于没有从intvector<>的转换,因此出现错误。

您将无法重载内置类型(如 int )的运算符。