C++ template string concatenation

后端 未结 5 891
天涯浪人
天涯浪人 2020-12-16 02:50

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

typedef const char CCTYPE[];
template struct StringConcat { ... };


        
相关标签:
5条回答
  • 2020-12-16 02:56

    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. The latter is trivial.

    0 讨论(0)
  • 2020-12-16 03:06
    #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. Nice exercise BTW.

    0 讨论(0)
  • 2020-12-16 03:06

    You can solve the problem of making your std::cout << StringConcat<foo, bar> work.

    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.

    0 讨论(0)
  • 2020-12-16 03:13

    Impossible. foo and bar are not compile time constants. 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);
    
    0 讨论(0)
  • 2020-12-16 03:19

    It is possible to take variable amounts of characters. However, I believe that there is no existing way to concatenate strings defined like that.

    0 讨论(0)
提交回复
热议问题