Aquarius_Girl
Aquarius_Girl

Reputation: 22906

How to pass a QVector as an optional argument to a function in c++?

Function declaration:

Q_INVOKABLE void formPackets (unsigned char          argPacketDescriptor,
                              unsigned char          argNoOfBytes,
                              QVector<unsigned char> argBody);

Third argument QVector should be optional.

I know that one way is to specify a default argument for QVector, but I don't know how to do that with a "QVector" or a "QList".

How to pass a QVector as an optional argument to a function in c++?

Upvotes: 2

Views: 1719

Answers (2)

hyde
hyde

Reputation: 62777

To use default argument, you need to provide the default value to use, when argument is missing. So simply this should work:

Q_INVOKABLE void formPackets (unsigned char          argPacketDescriptor,
                              unsigned char          argNoOfBytes,
                              QVector<unsigned char> argBody = QVector<unsigned char>());

For reference, here's doc link to QVector default constructor.


Above assumes, you don't need "no vector given" and "empty vector given" to mean different things. If you do need them to mean different things, then you need to provide separate overloads:

Q_INVOKABLE void formPackets (unsigned char          argPacketDescriptor,
                              unsigned char          argNoOfBytes,
                              QVector<unsigned char> argBody);

Q_INVOKABLE void formPackets (unsigned char          argPacketDescriptor,
                              unsigned char          argNoOfBytes);

Third Qt way would be to pass the 3rd argument as QVariant. Then you could have null QVariant mean no argument, and a QVector, empty or not, mean that argument exists. Function declaration:

Q_INVOKABLE void formPackets (unsigned char  argPacketDescriptor,
                              unsigned char  argNoOfBytes,
                              QVariant       argBody);

Upvotes: 3

Mateen Ulhaq
Mateen Ulhaq

Reputation: 27201

You have two options:

  1. Make two separate overloads.
  2. Specify a default argument.

I would prefer the first in most cases -- it is less likely to lead to trouble.

Upvotes: 2

Related Questions