我正在尝试了解更多有关运算符重载如何工作的信息。
我知道重载逗号运算符可能不是最好的主意,但这仅用于教学目的。
我期望以下代码使用我的重载运算符(我使用方括号,因为我知道逗号运算符的优先级最低)构造一个包含 (1,2) 的 vector ,然后调用该 vector 的赋值运算符。
但是,我得到一个错误:
no known conversion from argument 1 from 'int' to 'const std::vector<int>&'
我不明白为什么会这样。 (1,2) 应该构造一个 vector ,所以它不应该尝试从 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;
关于c++ - 运算符逗号重载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36901276/