c++ - 带有字符串操作解决方法的 constexpr?

标签 c++ c++11 stdstring constexpr

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

constexpr std::string foo() { return std::string("foo"); }
constexpr std::string bar() { return std::string("bar"); }
constexpr std::string foobar() { return foo() + bar(); }

最佳答案

编译时“字符串”连接:

#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
}

关于c++ - 带有字符串操作解决方法的 constexpr?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9050857/

相关文章:

c++ - 在类中使用重载运算符 new

c++ - 在 C++ 中排队 ..homework

c++ - 模板函数 - 模板是否覆盖普通函数

c++ - Visual Studio 2010 使用 std::string 编译错误?

c++ - GiNaC 未定义引用

c++ - 实现(自动项目: container) in VC2010

c++ - 是否有常量的 C++ 临时右值

c++ - 在 Qt 中使用 += 运算符时出错

c++ - 为什么 std::string append 不会在 rval ref 上重载?

c++ - Symbian:是否可以通过应用程序访问联系人列表?