Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
minimal named arguments for C++ 11
#include <iostream>
template<typename Lhs, typename Rhs>
struct assignment_t
{
using lhs_t = Lhs;
using rhs_t = Rhs;
lhs_t _lhs;
rhs_t _rhs;
};
template<typename T>
struct named_arg_t
{
using type = assignment_t<named_arg_t, T>;
auto operator=(T arg)
-> assignment_t<named_arg_t, T>
{
return { {}, arg };
}
};
// usage string:
named_arg_t<std::string> first_name{};
named_arg_t<std::string> second_name{};
void test_func(named_arg_t<std::string>::type first_name, named_arg_t<std::string>::type second_name)
{
auto firstname_val = first_name._rhs;
auto secondname_val = second_name._rhs;
std::cout << "first name=" << firstname_val
<< ", second name=" << secondname_val
<< std::endl;
}
// usage bool:
named_arg_t<bool> enable_widgets{};
void test_func_bool(const std::string& name, named_arg_t<bool>::type enable_widgets)
{
if(enable_widgets._rhs)
{
std::cout << "enable widgets for: " << name << std::endl;
}
}
// TEST:
int main(int argc, char* argv[])
{
test_func(first_name = "alfa", second_name = "beta");
//test_func("alfa"); -- too much, not supported!
test_func_bool("zeta", enable_widgets = true);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment