我正在尝试定义一些这样的可变参数模板:
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();
}
使用该构造,您应该能够在纯元编程中实现 FizzBuzz。不错的练习顺便说一句。
关于C++ 模板字符串连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4693819/