Last active
August 22, 2019 16:15
-
-
Save jbelloncastro/a7b26c231cee86d3fcffbe8969b6676d to your computer and use it in GitHub Desktop.
Embed string literals in a datatype
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 <array> | |
#include <tuple> | |
#include <string_view> | |
#include <utility> | |
template < class CharT, CharT... cs > | |
struct Literal { | |
static bool match( std::basic_string_view<CharT> s ) { | |
static constexpr std::array<CharT,sizeof...(cs)> value{cs...}; | |
return std::equal(value.begin(), value.end(), s.begin(), s.end()); | |
} | |
}; | |
template < class CharT, CharT... cs > | |
constexpr | |
Literal<CharT, cs...> operator ""_key() { | |
return {}; | |
} | |
template < class L, class T > | |
struct Mapping; | |
template < class CharT, CharT... cs, class T > | |
struct Mapping<Literal<CharT,cs...>, T> { | |
using key = Literal<CharT,cs...>; | |
using type = T; | |
}; | |
template < class T > | |
struct is_mapping : public std::false_type {}; | |
template < class L, class T > | |
struct is_mapping<Mapping<L,T>> : public std::true_type {}; | |
#define MEMBER(key,type) Mapping<decltype(key##_key),type> | |
template < class... Ps > | |
struct dispatcher { | |
template < size_t I > | |
size_t switch_( std::string_view ) { | |
return -1; // No match | |
} | |
template < size_t I, class Q, class... Qs > | |
size_t switch_( std::string_view s ) { | |
if( Q::key::match(s) ) | |
return I; | |
return switch_<I+1,Qs...>(s); | |
}; | |
size_t lookup( std::string_view s ) { | |
return switch_<0, Ps...>(s); | |
} | |
}; | |
using disp = dispatcher< | |
MEMBER("asdfasdfasdfasdf",int), | |
MEMBER("fdsafdsafdsafda",float), | |
MEMBER("qwert",std::string) | |
>; | |
int main( int argc, char* argv[] ) { | |
return disp().lookup(argv[1]); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment