logoalt Hacker News

Faking keyword arguments to functions in C++

22 pointsby ibobevlast Tuesday at 12:05 PM16 commentsview on HN

Comments

aleksiy123today at 4:44 AM

I pretty much always prefer using an options struct as soon as there is more than one optional argument.

Comes out cleaner because overriding a default argument doesn’t force you to also do all the positional arguments in front of it.

Designated initializers make it look really nice imo. I feel like the brackets are no big deal.

Python has sort of the opposite when you need to use *kwargs.

seeknotfindtoday at 3:14 AM

If you're calling this across translation units, the calling convention will come with a performance penalty, but boy have we come full circle since pre-ANSI C required you to pass args as a struct. Much love - wish the language required struct and arg list to be the same thing. You can send a list of em and it'll work with algebraic data types for batching calls. The dream. CPU doesn't play nice though since structs aren't register shaped, but maybe they could be in a future calling convention.

DaiPlusPlustoday at 3:25 AM

To me, “keyword arguments” means actual language keywords being used as arguments, like “minute” or “hour” in T-SQL’s DATEDIFF, for example: `SELECT DATEDIFF( hour, NOW(), someDateCol )`.

…but I think the author meant “named arguments”, like we have in C#, Swift, and Objective-C.

show 2 replies
kccqzytoday at 3:05 AM

That's a C99 feature, designated initializer. Hardly modern. Yes it was ported to C++ relatively late, but it happened in C++20.

show 2 replies
akoboldfryingtoday at 3:36 AM

Reminds me of an idea I had years ago, for implementing "named binary operator syntax" in C++ so that stuff like the following would work:

    int x = 5 <xor> 3; // x = 6
The basic trick was to notice that this is really parsed as:

    int x = ((5 < xor) > 3);
which you could implement with (roughly):

    struct XorType1 { ... } xor;

    struct XorType2 {
      int left;
      XorType2(int left) : left(left) {}
      int operator>(int right) const {
        return left ^ right;
      }
    };

    XorType2 operator<(int left, XorType1 const& ignored) {
      return XorType2(left);
    }
But I sat on this for a while and later discovered someone else had already come up with it :-/

EDIT: Thanks commenter hawkice for fixing my XOR arithmetic!

show 2 replies