简体   繁体   English

C ++模板字符串连接

[英]C++ template string concatenation

I'm trying to define some variadic template like that: 我正在尝试定义一些像这样的可变参数模板:

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

so that I could write sth like: 所以我可以这样写:

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

and it printed foobar . 它印刷了foobar How can I do this, if it's possible in C++0x? 如果C ++ 0x中有可能,我怎么能这样做呢?

my real interest is to solve FizzBuzz problem using c++ templates, I found a solution here to convert an int to char[] using templates. 我真正感兴趣的是使用c ++模板解决FizzBu​​zz问题,我在这里找到了一个解决方案,使用模板将int转换为char []。

You can solve the problem of making your std::cout << StringConcat<foo, bar> work. 你可以解决使你的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;
}

Now you can say 现在你可以说

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

Hope it helps. 希望能帮助到你。

#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();
}

Using that construct you should be able to implement your FizzBuzz in pure metaprogramming. 使用该构造,您应该能够在纯元编程中实现FizzBu​​zz。 Nice exercise BTW. 很棒的运动BTW。

Impossible. 不可能。 foo and bar are not compile time constants. foo和bar不是编译时常量。 There is also no reason to do this when you can use plain old functions: 当您可以使用普通的旧函数时,也没有理由这样做:

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

It is possible to take variable amounts of characters. 可以采用可变数量的字符。 However, I believe that there is no existing way to concatenate strings defined like that. 但是,我认为没有现成的方法来连接像这样定义的字符串。

You cannot concatenate two or more string literals expecting to get a single string literal (unless you want to use macros). 您不能连接两个或多个期望获得单个字符串文字的字符串文字(除非您想使用宏)。 But depending on the task at hand you can your template function return, for example, a std::string, which is a concatenation of string literals. 但是根据手头的任务,您的模板函数可以返回,例如,std :: string,它是字符串文字的串联。 The latter is trivial. 后者是微不足道的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM