The convenience of C++ default arguments

The convenience of C++ default arguments

Sometimes managing similar versions of two functions is too much work, so C++ provides a remedy: default parameters. The default parameter means that the default value of the function parameter has been set when the function is declared. If the function parameter value is not specified when the function is called, the default value at the time of declaration is used.

Application examples

The class BufContainer has the push method as follows:

#define GET_GPU_DATA 0x00

struct Item
{
    int dataSize;
    DWORD dataType;
    std::shared_ptr<uint8_t> data;
    LONGLONG dataTimeTag;
};

bool BufContainer::push(const uint8_t *pData, int dataSize)
{
    if(!pData || (dataSize <=0))
    {
        LOGE << "invaild data";
        return false;
    }
    Item item;
    item.dataSize = dataSize;
    item.dataType = GET_GPU_DATA;
    item.data = std::shared_ptr<uint8_t>(new uint8_t[dataSize], std::default_delete<uint8_t[]>());
    item.dataTimeTag = Timer::currentTick();
    memcpy((uint8_t *)item.data.get(), pData, dataSize);
    return addItemToQueue(&item);
}

The default dataType of Item in the code is GET_GPU_DATA, and the data in pData is encapsulated into Item format and added to the queue. The call to the push method is as follows:

(new BufContainer())->push(pInputBuf, iInputBufSize);

At this time, if you need to increase the type of datatype in Item but do not want to modify the call to the original push(const uint8_t *pData, int dataSize) method, modify the declaration of the push method as follows:

bool BufContainer::push(const uint8_t *pData, int dataSize, DWORD dataType = GET_GPU_DATA);

The corresponding push method is modified as follows:

bool BufContainer::push(const uint8_t *pData, int dataSize, DWORD dataType )
{
    if(!pData || (dataSize <=0))
    {
        LOGE << "invaild data";
        return false;
    }
    Item item;
    item.dataSize = dataSize;
    item.datayType = dataType;
    item.data = std::shared_ptr<uint8_t>(new uint8_t[dataSize], std::default_delete<uint8_t[]>());
    item.dataTimeTag = Timer::currentTick();
    memcpy((uint8_t *)item.data.get(), pData, dataSize);
    return addItemToQueue(&item);
}

.Keep
the original push method call format unchanged, and add dataType type as follows:

(new BufContainer())->push(pInputBufData, iInputBufDataSize, GET_GPU_CURSOR);

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325926058&siteId=291194637
Recommended