Last active
August 29, 2015 13:57
-
-
Save mrkkrj/9738989 to your computer and use it in GitHub Desktop.
minimal named arguments for C++ 11
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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