constexpr与字符串操作解决方法? [英] constexpr with string operations workaround?

查看:981
本文介绍了constexpr与字符串操作解决方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以前回答的问题解释了为什么我发布的代码下面不工作。我有一个后续问题:是否有一个解决方法是概念上等同的,即实现编译时字符串连接,但是实现方式是实际支持的C ++ 11?使用std :: string是完全不必要的。

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


推荐答案

编译时间字符串concatenation: p>

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
}

这篇关于constexpr与字符串操作解决方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆