Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

constexpr with string operations workaround?

This previously answered question explains why the code I have posted below does not work. I have a follow-up question: is there a workaround that is conceptually equivalent, i.e., achieves compile-time string concatenation, but is implemented in a way that is actually supported by C++11? Using std::string is completely non-essential.

constexpr std::string foo() { return std::string("foo"); }
constexpr std::string bar() { return std::string("bar"); }
constexpr std::string foobar() { return foo() + bar(); }
like image 622
andrew.corrigan Avatar asked Dec 27 '22 07:12

andrew.corrigan


2 Answers

Compile-time "string" concatenation :

#include <iostream>
#include <string>

template <char ... CTail>
struct MetaString
{ 
    static std::string string()
    {
        return std::string{CTail...};
    }
};

template <class L, class R>
struct Concatenate;

template <char ... LC, char  ... RC>
struct Concatenate<MetaString<LC ... >, MetaString<RC ... >>
{
    typedef MetaString<LC ..., RC ... > Result;
};

int main()
{
    typedef MetaString<'f', 'o', 'o'> Foo;
    typedef MetaString<'b', 'a', 'r'> Bar;

    typedef typename Concatenate<Foo, Bar>::Result FooBar;

    std::cout << Foo::string() << std::endl; //  foo
    std::cout << Bar::string() << std::endl; //  bar
    std::cout << FooBar::string() << std::endl; //  foobar
}
like image 200
Denis Kreshikhin Avatar answered Jan 07 '23 23:01

Denis Kreshikhin


Sprout C++ Libraries provide constexpr string. see: https://github.com/bolero-MURAKAMI/Sprout/blob/master/libs/string/test/string.cpp

like image 37
Akira Takahashi Avatar answered Jan 07 '23 22:01

Akira Takahashi