Felix Dombek
Felix Dombek

Reputation: 14372

C++ elegant way of passing (a subset of) options to a function

I have a function whose exact behaviour is controlled by a set of flags. Most of these are usually false. Having them all as parameters quickly becomes very messy.

I could create an enum for the flags:

enum ParseFlags { assignmentPossible = 1, commaDelimits = 2, isConst = 4 };
PExpression ParseExpr(unsigned int flags);

A bit better: now, when calling the function, I only have to specify the values I want to set, instead of a long list of bools.

However, I would like to know if there is a more elegant or more general way of passing a subset of options to a function. What if I have non-boolean options?

I'm looking for a C++ (Boost is ok) way to call a function like:

ParseExpr({ isConst: true; maxDepth: 5 });

where I can omit all values that I want to leave at their default.

What techniques and/or libraries exist for this?

Upvotes: 4

Views: 438

Answers (1)

Passer By
Passer By

Reputation: 21160

Ripping from this library's design, you could have a parameter class which curries its set methods.

class ParseFlags
{
public:
    ParseFlags& assignable(bool b) {assignable_ = b; return *this;}
    ParseFlags& delimiter(char c) {delimiter_ = c; return *this;}
    ParseFlags& constness(bool b) {constness_ = b; return *this;}
private:
    bool assignable_ = false;
    char delimiter_ = ',';
    bool constness_ = false;
};

PExpression ParseExpr(const ParseFlags& = ParseFlags{});

Call it like

auto exp = ParseExpr(ParseFlags().constness(false).delimiter('.'));
auto exp2 = ParseExpr();

Which is almost as good as having named parameters.

Upvotes: 5

Related Questions