C++模板字符串连接

vis*_*ssi 10 c++ string templates metaprogramming c++11

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

typedef const char CCTYPE[];
template<CCTYPE X, CCTYPE... P> struct StringConcat { ... };
Run Code Online (Sandbox Code Playgroud)

所以我可以这样写:

char foo[] = "foo"; char bar[] = "bar";
std::cout << StringConcat<foo, bar>;
Run Code Online (Sandbox Code Playgroud)

它打印出来了foobar.如果C++ 0x中有可能,我怎么能这样做呢?

我真正感兴趣的是使用c ++模板解决FizzBu​​zz问题,我在这里找到了一个解决方案,使用模板将int转换为char [].

Joh*_*itb 5

你可以解决你的std::cout << StringConcat<foo, bar>工作问题.

template<CCTYPE...> struct StrBag {};
template<CCTYPE ...Str> void StringConcat(StrBag<Str...>) {}

std::ostream &print(std::ostream &os) { 
  return os; 
}

template<typename ...T> 
std::ostream &print(std::ostream &os, CCTYPE t1, T ...t) { 
  os << t1; 
  return print(os, t...);
}

template<CCTYPE ...Str>
std::ostream &operator<<(std::ostream &os, void(StrBag<Str...>)) {
  return print(os, Str...) << std::endl;
}
Run Code Online (Sandbox Code Playgroud)

现在你可以说

char foo[] = "foo"; char bar[] = "bar";
int main() {
  std::cout << StringConcat<foo, bar> << std::endl;
}
Run Code Online (Sandbox Code Playgroud)

希望能帮助到你.


Edw*_*nge 5

#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();
}
Run Code Online (Sandbox Code Playgroud)

使用该构造,您应该能够在纯元编程中实现FizzBu​​zz.很棒的运动BTW.