Skip to content

Instantly share code, notes, and snippets.

@MiSawa
Last active August 29, 2015 14:23
Show Gist options
  • Save MiSawa/61c04ca066e5fcd9d2b6 to your computer and use it in GitHub Desktop.
Save MiSawa/61c04ca066e5fcd9d2b6 to your computer and use it in GitHub Desktop.
#include <bits/stdc++.h>
using namespace std;
namespace KeyWordArguments{//{{{
template<typename T>
class KeyWord {//{{{
using type = T;
KeyWord(const size_t &id, const T &val) : id(id), val(val) {}
static inline size_t get_id(){ static size_t count = 0; return count++; }
public:
const size_t id;
const T val;
constexpr KeyWord() : id(get_id()), val() {}
constexpr explicit KeyWord(const T &val) : id(get_id()), val(val) {}
KeyWord<T> operator=(const T &val) const { return KeyWord(id, val); }
KeyWord<T> operator||(const T &val) const { return KeyWord(id, val); }
};//}}}
template<typename ...Ts> class ArgHolder;
template<> class ArgHolder<> {//{{{
public:
template<typename T> bool has(const KeyWord<T> &keyword) const {
return false;
}
template<typename T> T operator[](const KeyWord<T> &keyword) const {
return keyword.val;
}
};//}}}
template<typename T, typename ...kTs> class ArgHolder<KeyWord<T>, kTs...> {//{{{
const KeyWord<T> car;
const ArgHolder<kTs...> cdr;
public:
ArgHolder(const KeyWord<T> &car, const kTs &...cdr) : car(car), cdr(cdr...) {}
bool has(const KeyWord<T> &keyword) const {
return keyword.id == car.id ? car.val : cdr.has(keyword);
}
template<typename U>
bool has(const KeyWord<T> &keyword) const {
return cdr.has(keyword);
}
T operator[](const KeyWord<T> &keyword) const {
return keyword.id == car.id ? car.val : cdr[keyword];
}
template<typename U>
U operator[](const KeyWord<U> &keyword) const {
return cdr[keyword];
}
};//}}}
template<typename ...Args>
ArgHolder<Args...> compile(const Args &...args) {//{{{
return ArgHolder<Args...>(args...);
}//}}}
}//}}}
using KeyWordArguments::KeyWord;
KeyWord<int> key;
KeyWord<string> word;
KeyWord<char> argument('f'); // default argument
template<typename ...Args>
void func(const Args &..._args){
auto args = compile(_args...); // ADL すげぇ.
cout << args[key] << endl;
cout << args[word] << endl;
cout << args[argument] << endl;
cout << args[argument || 'x'] << endl; // overwrite default argument
}
int main(){
func(key = 42, word = "foo");
return 0;
}
// vim:set foldmethod=marker commentstring=//%s:
// 一方ロシアは
#include <bits/stdc++.h>
using namespace std;
struct Arg{
int hoge;
string fuga;
int fizz;
};
void func(const Arg &arg){
cout << arg.hoge << " " << arg.fuga << endl;
}
int main(){
func({ .hoge = 42,
.fuga = "foo"
});
return 0;
}
// vim:set foldmethod=marker commentstring=//%s:
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment