Skip to content

Instantly share code, notes, and snippets.

@jbelloncastro jbelloncastro/literal.hpp
Last active Aug 22, 2019

Embed
What would you like to do?
Embed string literals in a datatype
#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
You can’t perform that action at this time.