Last active
December 3, 2021 20:08
-
-
Save charlesnicholson/5f066d9f0ea2f7b484ac to your computer and use it in GitHub Desktop.
compile-time string concatenation
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 <cstdio> | |
namespace detail { | |
template<unsigned count, template<unsigned...> class meta_functor, unsigned... indices> | |
struct apply_range { | |
typedef typename apply_range<count - 1, meta_functor, count - 1, indices...>::result result; | |
}; | |
template<template<unsigned...> class meta_functor, unsigned... indices> | |
struct apply_range<0, meta_functor, indices...> { | |
typedef typename meta_functor< indices... >::result result; | |
}; | |
template<char... str> struct string { | |
static constexpr const char c_str[sizeof...(str) + 1] = { str..., '\0' }; | |
}; | |
template<char... str> constexpr const char string<str...>::c_str[sizeof...(str) + 1]; | |
template<typename lambda_result> struct string_builder { | |
template<unsigned... indices> struct apply { | |
typedef string<lambda_result{}.chars[indices]...> result; | |
}; | |
}; | |
template< char... lhs, char... rhs > | |
string< lhs..., rhs... > operator +(string< lhs... >, string< rhs... >) { return {}; } | |
} | |
#define MAKE_STRING(string_literal) \ | |
[]{ \ | |
struct constexpr_string_type { const char *chars = string_literal; }; \ | |
return detail::apply_range<sizeof(string_literal) - 1, detail::string_builder< constexpr_string_type >::apply>::result{}; \ | |
}() | |
int main() { | |
auto hello = MAKE_STRING("hello"); | |
auto world = MAKE_STRING(" world"); | |
auto test = MAKE_STRING(" test"); | |
std::printf("compile concat: %s\n", (hello + world + test).c_str); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Cleaned up generated assembly with debug instructions + markers removed. Compiled with: