Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enforce type safety in C++ without using extra classes

I am somewhat familiar with type safety, and have used it successfully before in methods which receive several parameters of the same type (bool) to avoid confusion. For example:

// Old version of the method
void sendPackage(bool sendImmediately, bool dividePacket);

// Type safe version
enum SendImmediatelyPreference
{
    SEND_IMMEDIATELY,
    DO_NOT_SEND_IMMEDIATELY
};

enum PacketDivisionPreference
{
    DIVIDE_PACKET,
    DO_NOT_DIVIDE_PACKET
};

void sendPackage(
    SendImmediateltPreference immediatePref,
    PacketDivisionPreference divisionPref);

So the cryptic sendPackage(true, false) becomes sendPackage(SEND_IMMEDIATELY, DO_NOT_DIVIDE_PACKET).

The problem is that this is only an option for bool. I have a method that accepts several std::vector<std::string> and I'd like to minimise the posibility of the user inputting the arguments in the wrong order.

I can think of creating different classes which contains an std::vector<std::string> and either override tons of the std::vector methods or expose the internal vector.

Is there an easier way, some sort of typedef which enforces type safety? Using boost would be okay.

like image 334
user2891462 Avatar asked Jul 09 '26 09:07

user2891462


1 Answers

How about an alternative approach using named parameters? There are several ways of going about this in C++ described here. The tag approach using a tuple looks reasonable. There is also boost parameter.

This doesn't offer strong type safety, but you could argue that the user is just as likely to call the wrong constructor to make their type safe object as they are to use the wrong tag when calling your function. This situation is less likely to occur if the types are used throughout your application vs defined only for one particular function.

See also the discussion of boost strong typedef vs parameter for a similar purpose here.

like image 190
Mitchell Kline Avatar answered Jul 11 '26 10:07

Mitchell Kline



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!