constexpr with string operations workaround?

Deadly 提交于 2019-12-05 00:51:36

问题


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(); }

回答1:


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
}



回答2:


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



来源:https://stackoverflow.com/questions/9050857/constexpr-with-string-operations-workaround

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!