【发布时间】:2021-02-24 08:52:25
【问题描述】:
“我不是专业人士,我只是在学习!”
我想在我的类中支持添加运算符,例如 Buffer。
class Buffer : public vector<uint8_t>
{
public:
Buffer() = default;
Buffer& operator += (const char* str)
{
auto pStr = str;
while(*pStr)
{
emplace_back(*pStr);
++pStr;
}
return *this;
}
template<typename T>
Buffer& operator += (const initializer_list<T>& ByteArray)
{
this->operator+=<vector<T>>(ByteArray);
return *this;
}
template<class OtherContainer>
Buffer& operator += (const OtherContainer& ByteArray)
{
std::copy(ByteArray.begin(), ByteArray.end(), std::back_inserter(*this));
return *this;
}
template<typename T, size_t size>
Buffer& operator += (const T (& arr)[ size ] )
{
std::copy( std::begin( arr ), std::end( arr ), std::back_inserter(*this));
return *this;
}
};
我想覆盖:
int main()
{
vector<uint8_t> vec = {48,49,50,51};
string str = "45";
char arr[] = {60,61,62,63};
Buffer b;
b += vec;
b += str;
b += "67";
b += {56,57,58,59};
b += arr;
return 0;
}
是否可以为所有情况编写一个漂亮的模板?或者至少组合成一个“initializer_list”、“vector”、“string”?也许在某个地方您可以避免“复制”并使用“移动”?
【问题讨论】:
-
容器和 c-array 可能会合并。
标签: c++ templates containers operator-overloading