Topic: Keyword arguments (was: Strong named arguments as


Author: Ross Smith <ross.smith@otoy.com>
Date: Fri, 13 Jul 2018 09:22:53 +1200
Raw View
For whatever it's worth, I have a simple implementation of keyword
arguments (inspired by Python's "kwargs") that I've frequently
found useful for some time now.

Implementation:

template <typename T, int ID> struct Kwptr_ { const T* ptr; };
template <typename T, int ID = 0> struct Kwarg
     { constexpr Kwptr_<T, ID> operator=(const T& t) const noexcept
     { return {&t}; } };
template <typename T, int ID> T kwget(Kwarg<T, ID>, const T& def)
     { return def; }
template <typename T, int ID, typename... Args>
     T kwget(Kwarg<T, ID>, const T&, Kwptr_<T, ID> p, Args...)
     { return *p.ptr; }
template <int ID, typename... Args>
     bool kwget(Kwarg<bool, ID>, bool, Kwarg<bool, ID>, Args...)
     { return true; }
template <typename T, int ID, typename Arg1, typename... Args>
     T kwget(Kwarg<T, ID> key, const T& def, Arg1, Args... args)
     { return kwget(key, def, args...); }

Define a set of keywords using Kwarg<T> (the optional ID parameter
is only needed to distinguish between different keywords with the
same argument type); pass them to a variadic function template;
parse the arguments inside the function using kwget(). At the call
site, keyword arguments look like "keyword=value", or just the
bare keyword if it's a boolean.

(The Kwptr_ template is an implementation detail.)

Typical usage:

class Window {
public:
     static constexpr Kwarg<int, 1> width = {};
     static constexpr Kwarg<int, 2> height = {};
     static constexpr Kwarg<string> title = {};
     static constexpr Kwarg<bool> visible = {};
     template <typename... Args> explicit Window(Args... args) {
         int w = kwget(width, 640, args...);
         int h = kwget(height, 480, args...);
         string label = kwget(title, "New Window"s, args...);
         bool vis = kwget(visible, false, args...);
         // ...
     }
};

Window app_window(Window::title="Hello World",
     Window::width=1000, Window::height=750,
     Window::visible);

Ross Smith

--
You received this message because you are subscribed to the Google Groups "ISO C++ Standard - Future Proposals" group.
To unsubscribe from this group and stop receiving emails from it, send an email to std-proposals+unsubscribe@isocpp.org.
To post to this group, send email to std-proposals@isocpp.org.
To view this discussion on the web visit https://groups.google.com/a/isocpp.org/d/msgid/std-proposals/9f7f6a30-4008-248f-e1c4-71c707e95153%40otoy.com.

.