Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ combining arguments template metaprogramming

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

like image 919
Robert Dijkstra Avatar asked Sep 29 '22 15:09

Robert Dijkstra


2 Answers

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...}){}
};
like image 133
Pradhan Avatar answered Oct 05 '22 08:10

Pradhan


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()
like image 27
tux3 Avatar answered Oct 05 '22 06:10

tux3