I am new to templates and metaprogramming in C++. What I am trying to do now is the following: I have a struct with a template that expects non-type variadic pack of type char, defined trivially as follows:
template <char ... chs>
struct MyStruct
{};
I have a second struct template which expects two types, like this:
template <typename ch1, typename ch2>
struct Together
{
};
What I'm trying to achieve is:
cout << Together<MyStruct<'a','b'>, MyStruct<'c','d'>>::result << '\n';
Which has to print: abcd
Thanks in advance
With templates, you can achieve pattern-matching through partial specialization. Declare a primary template declaration like this:
template <typename First, typename Second>
struct Together;
and then define a partial specialization for types with "look" a certain way:
template <char... ch1s, char... ch2s>
struct Together<MyStruct<ch1s...>, MyStruct<ch2s...>>
{
std::string result;
Together() : result({ch1s..., ch2s...}){}
};
This is a possible solution that closely matches the question using a std::string result :
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;
}
It will of course work with more or less template parameters, like this :
Together<MyStruct<'a','b','c','d'>, MyStruct<'e','f','g'>>::result()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With