Search code examples
c++17variadic-templatesstring-concatenationconstexpr-function

Concatenate string literals at compile time


I need to concatenate a variable number of string literals into one to use it in static_assert()

I tried using templates with structs, but compiler does not like literals as template parameters.

error: the address of ‘m1’ is not a valid template argument because it does not have static storage duration.
error: ‘"thre"’ is not a valid template argument for type ‘const char*’ because string literals can never be used in this context

I also tried perfect forwarding, but I get an error: ‘args#0’ is not a constant expression

template<size_t size>
constexpr size_t const_strssize(const char (&)[size]) {
        return size;
}

template<class... Ts> 
constexpr size_t const_strssize(Ts&&... args) {
        return const_sum<(const_strssize(std::forward<const Ts>(args)), ...)>::get;
}

Just to clarify, I cannot do "string1" "string2" because some of the strings I get from functions returns.

Please, do not advise stuff like strlen or memcpy. I know, they can be calculated at compile time.


Solution

  • static_assert() is specified to accept string literal. Any constexpr function you can write can return a constant, but not literal. So you only may use preprocessor to construct strings for static_assert. Sorry.