C ++模板字符串连接 [英] C++ template string concatenation

查看:115
本文介绍了C ++模板字符串连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图定义一些可变参数模板:

I'm trying to define some variadic template like that:

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

,这样我就可以编写sth:

so that I could write sth like:

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

并打印 foobar
我如何能做到这一点,如果可能在C + + 0x?

and it printed foobar. How can I do this, if it's possible in C++0x?

我真正的兴趣是解决 FizzBu​​zz 问题使用c ++模板,我发现一个解决方案此处使用模板将int转换为char []。

my real interest is to solve FizzBuzz problem using c++ templates, I found a solution here to convert an int to char[] using templates.

推荐答案

#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。尼斯练习BTW。

Using that construct you should be able to implement your FizzBuzz in pure metaprogramming. Nice exercise BTW.

这篇关于C ++模板字符串连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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