Skip to content

Instantly share code, notes, and snippets.

@dwilliamson
Created February 5, 2018 13:55
Show Gist options
  • Save dwilliamson/593a61e17d8195c96ce23ed71e138e80 to your computer and use it in GitHub Desktop.
Save dwilliamson/593a61e17d8195c96ce23ed71e138e80 to your computer and use it in GitHub Desktop.
C++11 string-to-type
#include <stdio.h>
int main()
{
using T = TYPE_STRING("helo");
printf("%s\n", T::string);
}
template <char... C>
struct TypeString
{
static constexpr const char string[sizeof...(C)+1] = { C...,'\0' };
};
template <int N, int M>
constexpr char GetChar(char const(&c)[M])
{
return N < M ? c[N] : 0;
}
#define TYPE_STRING(str) TypeString< \
GetChar<0>(str), \
GetChar<1>(str), \
GetChar<2>(str), \
GetChar<3>(str), \
GetChar<4>(str), \
GetChar<5>(str), \
GetChar<6>(str), \
GetChar<7>(str), \
GetChar<8>(str), \
GetChar<9>(str), \
GetChar<10>(str), \
GetChar<11>(str), \
GetChar<12>(str), \
GetChar<13>(str), \
GetChar<14>(str), \
GetChar<15>(str), \
GetChar<16>(str), \
GetChar<17>(str), \
GetChar<18>(str), \
GetChar<19>(str), \
GetChar<20>(str), \
GetChar<21>(str), \
GetChar<22>(str), \
GetChar<23>(str), \
GetChar<24>(str), \
GetChar<25>(str), \
GetChar<26>(str), \
GetChar<27>(str), \
GetChar<28>(str), \
GetChar<29>(str), \
GetChar<30>(str), \
GetChar<31>(str) \
>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment