Jac*_*ack 5 c++ vector operator-overloading c++11
我正在尝试了解有关运算符重载如何工作的更多信息.
我知道重载逗号运算符可能不是最好的主意,但这只是出于教学目的.
我期待以下代码使用我的重载运算符(我使用括号,因为我知道逗号运算符具有最低优先级)来构造包含(1,2)的向量,然后调用向量的赋值运算符.
但是,我收到一个错误:
no known conversion from argument 1 from 'int' to 'const std::vector<int>&'
Run Code Online (Sandbox Code Playgroud)
我不明白为什么会这样.(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;
}
Run Code Online (Sandbox Code Playgroud)
Ben*_*ley 19
应用于整数的逗号运算符已有内置定义.您的模板甚至没有运行重载解析,因为除非至少有一个参数是用户定义的类型,否则不能重载运算符.
你可以这样做:
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();
}
Run Code Online (Sandbox Code Playgroud)
或者看看Boost.Assign,它允许这样的结构:
std::vector<int> a;
a += 1,2,3,4,5,6,7,8;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1513 次 |
| 最近记录: |