C ++ combining metaprogramming pattern templates

I am new to templates and metaprogramming in C ++. What I'm trying to do now is this: I have a structure with a template that expects a non-pig variational package of type char, which is defined trivially as follows:

template <char ... chs> struct MyStruct {}; 

I have a second structure template that expects two types, for example:

 template <typename ch1, typename ch2> struct Together { }; 

I am trying to achieve:

 cout << Together<MyStruct<'a','b'>, MyStruct<'c','d'>>::result << '\n'; 

Printable: abcd

Thanks in advance

+5
source share
3 answers

Using templates, you can achieve pattern matching through partial specialization. Declare the declaration of the main template as follows:

 template <typename First, typename Second> struct Together; 

and then define partial specialization for types with a “look” in a certain way:

 template <char... ch1s, char... ch2s> struct Together<MyStruct<ch1s...>, MyStruct<ch2s...>> { std::string result; Together() : result({ch1s..., ch2s...}){} }; 
+3
source

This is a possible solution that exactly matches the query using the result of std :: string:

 template <char ... chs> struct MyStruct { static string stringify() { return stringify(chs...); } template <typename ... cst> static string stringify() { return string(); } template <typename T, typename ... cst> static string stringify(T c, cst... cs) { return string() + c + stringify<cst...>(cs...); } }; template <typename ch1, typename ch2> struct Together { static string result() {return ch1::stringify() + ch2::stringify();} }; int main() { cout << Together<MyStruct<'a','b'>, MyStruct<'c','d'>>::result() << '\n'; return 0; } 

Of course, it will work with more or less template parameters, for example:

 Together<MyStruct<'a','b','c','d'>, MyStruct<'e','f','g'>>::result() 
+1
source

Following is a slight improvement @ Ryan Haining :

 template <char... Chars> struct MyStruct { static constexpr char value[] {Chars..., '\0'}; }; template <char... Chars> constexpr char MyStruct<Chars...>::value[]; template <typename, typename> struct Together; template <char... Chars1, char... Chars2> struct Together<MyStruct<Chars1...>, MyStruct<Chars2...>> { using type = MyStruct<Chars1..., Chars2...>; }; 

Live demo

0
source

Source: https://habr.com/ru/post/1214434/


All Articles