C++ 模板字符串连接

标签 c++ string templates metaprogramming c++11

我正在尝试定义一些这样的可变参数模板:

typedef const char CCTYPE[];
template<CCTYPE X, CCTYPE... P> struct StringConcat { ... };

这样我就可以这样写:

char foo[] = "foo"; char bar[] = "bar";
std::cout << StringConcat<foo, bar>;

它打印了foobar。 如果在 C++0x 中可行,我该怎么做?

我真正感兴趣的是解决FizzBuzz使用 C++ 模板时出现问题,我找到了解决方案 here使用模板将 int 转换为 char[]。

最佳答案

#include <boost/mpl/string.hpp>
#include <boost/mpl/insert_range.hpp>
#include <boost/mpl/end.hpp>
#include <iostream>

using namespace boost;

template < typename Str1, typename Str2 >
struct concat : mpl::insert_range<Str1, typename mpl::end<Str1>::type, Str2> {};

int main()
{
  typedef mpl::string<'hell', 'o'> str1;
  typedef mpl::string<' wor', 'ld!'> str2;

  typedef concat<str1,str2>::type str;

  std::cout << mpl::c_str<str>::value << std::endl;

  std::cin.get();
}

使用该构造,您应该能够在纯元编程中实现 FizzBu​​zz。不错的练习顺便说一句。

关于C++ 模板字符串连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4693819/

相关文章:

Android解析json的问题

c++ - 是否可以在 C++14 中分配和验证 constexpr 结构?

C++ 静态结构模板方法返回枚举类型

c++ - 评估对象的创建是什么意思?

c++ - 交换功能的好处?

c++ - 正确使用 boost::is_upper

Java 字符串构造函数

C++ : display a bar chart of array data using *

asp.net - 如何在VB.NET中找出字符串的第一个字符是否是数字?

templates - 为什么我的 Magento 产品页面的评论部分没有显示?