从函数为std :: vector创建自定义扩展名

问题描述 投票:0回答:1

我正在尝试学习一些来自C#的C ++。我在C#中喜欢的一件事是CustomItem.ToString()之类的扩展,并且很好奇我如何在C ++中实现类似的东西。我正在使用std::vector<unsigned char>存储缓冲区,然后逐字节处理它。

我具有以下功能:

int DataParser::ToLittleEndianInt(std::vector<unsigned char> ba) //Little Endian
{
    long int Int = 0;
    int arraySize = ba.size();
    if (arraySize ==4)
    {
        Int = ba[0] | ((int)ba[1] << 8) | ((int)ba[2] << 16) | ((int)ba[3] << 24);
    }
    else if (arraySize == 2)
    {
        Int = ba[0] | ((int)ba[1] << 8);
    }
    else if (arraySize == 1)
    {
        Int = ba[0];
    }
    return Int;
}

这里我可以向它发送一个从1到4字节的向量,它将为我转换为整数。有没有办法让我像这样使用它:

std::vector<unsigned char> CurrentBytes(4);
for (int i = 0; i < 4; i++)
    CurrentBytes[i]=1;

// how can we do this?
int results = CurrentBytes.ToLittleEndianInt();
//or
int results = CurrentBytes->ToLittleEndianInt();

我只是觉得它很易读,并且想要对字符串,日期,整数,美元等进行扩展。

c++ extension-methods
1个回答
0
投票

这就是发明继承的原因。从std :: vector继承您的类,添加所需的任何功能(但不添加数据成员)并使用您自己的类型:

#include<vector>

template <typename T>
class myVector : public std::vector<T>
{    
    public:
    myVector(int n): std::vector<T>(n) {}

    int ToLittleEndianInt()
    {
        //your ToLittleEndianInt() definition...
        return 0;
    }
};

int main()
{
    myVector<unsigned char> CurrentBytes(4);
    for (int i = 0; i < 4; i++)
        CurrentBytes[i]=1;

    int results = CurrentBytes.ToLittleEndianInt();
}

但是它可能无法与其他STL接口(例如算法)一起使用。

© www.soinside.com 2019 - 2024. All rights reserved.