Skip to content

Instantly share code, notes, and snippets.

@alexeiz
Created July 19, 2012 18:43
Show Gist options
  • Save alexeiz/3145918 to your computer and use it in GitHub Desktop.
Save alexeiz/3145918 to your computer and use it in GitHub Desktop.
Named arguments in C++ (a bare bones concept)
#include <iostream>
#include <ostream>
#define DEFINE_NAMED_ARG(type, arg_name, arg_type) \
struct type \
{ \
type(arg_type val = arg_type()) \
: val_(val) \
{} \
\
operator arg_type() const \
{ \
return val_; \
} \
\
private: \
arg_type val_; \
}; \
\
struct type ## _tag \
{ \
type operator=(arg_type val) const \
{ \
return type(val); \
} \
}; \
\
type ## _tag arg_name; \
DEFINE_NAMED_ARG(year_t, year, int);
DEFINE_NAMED_ARG(month_t, month, int);
DEFINE_NAMED_ARG(day_t, day, int);
void print_date(year_t year, month_t month, day_t day)
{
std::cout << month << '/' << day << '/' << year << std::endl;
}
int main()
{
print_date(year = 2012, month = 6, day = 7);
print_date(2012, 12, 1);
// won't compile:
// print_date(month = 6, year = 2012, day = 7);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment