运算符逗号重载

Operator comma overloading

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

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

我期望以下代码使用我的重载运算符(我使用方括号,因为我知道逗号运算符的优先级最低)构造一个包含 (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>。您正在尝试将 2(一个 int)分配给 a(一个 vector<int>),并且由于没有从 intvector<> 你得到错误。

您将无法重载内置类型的运算符,例如 int