fork download
  1. #include <iostream>
  2. #include <string>
  3. #include <string.h>
  4.  
  5. class NullType {};
  6.  
  7. template <typename T, typename U>
  8. struct Typelist
  9. {
  10. typedef T Head;
  11. typedef U Tail;
  12. };
  13.  
  14. template <typename T, typename TL>
  15. struct StringChain
  16. {
  17. StringChain(const T& t, const StringChain<typename TL::Head, typename TL::Tail>& tl) : head(t), tail(tl) {}
  18.  
  19. template <typename X>
  20. StringChain<X, Typelist<T, TL> > operator()(const X& obj) const
  21. {
  22. return StringChain<X, Typelist<T, TL> >(obj, *this);
  23. }
  24.  
  25. size_t getSize() const
  26. {
  27. return tail.getSize() + doGetSize(head);
  28. }
  29.  
  30. void appendString(char* str_ptr, size_t& offset) const
  31. {
  32. tail.appendString(str_ptr, offset);
  33. offset += doAppendString(str_ptr + offset, head);
  34. }
  35.  
  36. std::string str() const
  37. {
  38. std::string ret_string;
  39. ret_string.resize(getSize());
  40. size_t offset = 0;
  41. appendString(&ret_string[0], offset);
  42. return ret_string;
  43. }
  44.  
  45. const T& head;
  46. const StringChain<typename TL::Head, typename TL::Tail>& tail;
  47. };
  48.  
  49. template <>
  50. struct StringChain<NullType, NullType>
  51. {
  52. public:
  53. template <typename X>
  54. StringChain<X, Typelist<NullType, NullType> > operator()(const X& obj) const
  55. {
  56. return StringChain<X, Typelist<NullType, NullType> >(obj, *this);
  57. }
  58.  
  59. size_t getSize() const
  60. {
  61. return 0;
  62. }
  63.  
  64. void appendString(char*, size_t&) const
  65. {
  66. return;
  67. }
  68. };
  69.  
  70.  
  71. template <size_t N>
  72. size_t doGetSize(const char (&array)[N])
  73. {
  74. return strnlen(array, N);
  75. }
  76.  
  77. template <size_t N>
  78. size_t doAppendString(char* str_ptr, const char (&array)[N])
  79. {
  80. size_t length = doGetSize(array);
  81. memcpy(str_ptr, array, length);
  82. return length;
  83. }
  84.  
  85. typedef StringChain<NullType, NullType> StrChain;
  86.  
  87. int main()
  88. {
  89. std::cout << StrChain()("hello")(" ")("world")("!!").str() << std::endl;
  90. return 0;
  91. }
  92.  
  93.  
Success #stdin #stdout 0.01s 2856KB
stdin
Standard input is empty
stdout
hello world!!