Skip to content

Instantly share code, notes, and snippets.

@Little-Ki
Last active September 18, 2023 03:47
Show Gist options
  • Save Little-Ki/1dc802e3886ba72a871368054e018043 to your computer and use it in GitHub Desktop.
Save Little-Ki/1dc802e3886ba72a871368054e018043 to your computer and use it in GitHub Desktop.
[C++ Template] Fixed string ( < c++ 20 )
template<char ...c>
struct string{
constexpr static size_t N = sizeof...(c) + 1;
constexpr static const char data[N] = { c..., 0 };
};
template<char ...C>
auto make_string(string<C...>) -> string<C...>;
template<char ...C1, char C,char ...C2>
auto make_string(string<C1...>, string<C>, string<C2>...) ->
decltype(make_string(string<C1...,C>{}, string<C2>{}...));
template<char ...C1, char ...C2>
auto make_string(string<C1...>, string<'\0'>, string<C2>...) ->
string<C1...>;
template<char ...C>
auto tiny_string(string<C...>) ->
decltype(make_string(string<C>{}...));
template<size_t M, size_t N>
constexpr char char_of_string(const char(&arr)[N])
{
return arr[M < N ? M : N - 1];
};
#define MAKE_CHARS(n, str) \
char_of_string<0x##n##0>(str), char_of_string<0x##n##1>(str), char_of_string<0x##n##2>(str), char_of_string<0x##n##3>(str),\
char_of_string<0x##n##4>(str), char_of_string<0x##n##5>(str), char_of_string<0x##n##6>(str), char_of_string<0x##n##7>(str),\
char_of_string<0x##n##8>(str), char_of_string<0x##n##9>(str), char_of_string<0x##n##A>(str), char_of_string<0x##n##B>(str),\
char_of_string<0x##n##C>(str), char_of_string<0x##n##D>(str), char_of_string<0x##n##E>(str), char_of_string<0x##n##F>(str)
#define MAKE_CHARS_128(str) \
MAKE_CHARS(0,str), MAKE_CHARS(1,str),\
MAKE_CHARS(2,str), MAKE_CHARS(3,str),\
MAKE_CHARS(4,str), MAKE_CHARS(5,str),\
MAKE_CHARS(6,str), MAKE_CHARS(7,str)
#define MAKESTRINGCHAR(str) decltype(make_string(string<MAKE_CHARS_128(str)>{}))
#define MAKESTRINGTINY(str) decltype(tiny_string(string<MAKE_CHARS_128(str)>{}))
// MAKESTRINGTINY("hello, word") str;
// --> decltype(tiny_string(string<MAKE_CHARS_128("hello, word")))
// --> decltype(tiny_string(string<char_of_string<0x00>("hello, word"), ...))
// --> decltype(tiny_string('h', 'e', 'l', 'l', ..., '\0', ...)))
// --> decltype(make_string(string<'h'>{}, string<'e'>{}, ...))
// --> decltype(make_string(string<'h', 'e'>{}, string<'l'>{}, ...))
// --> decltype(make_string(string<'h', 'e', 'l'>{}, string<'l'>{}, ...))
// --> decltype(make_string(string<'h', 'e', 'l', ..., '\0'>{}, ...))
// --> decltype(make_string(string<'h', 'e', 'l', ...>{}, string<'\0'>{}, ...))
// --> string<'h','e','l', ..., 'o'>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment