Home > Mobile >  Variadic template: inline pattern expansion
Variadic template: inline pattern expansion

Time:07-27

C variadic templates can use patterns where you can repeat blocks surrounding the variadic argument, like so:

template<typename... Args>
struct MyStruct : seq<pair<Other, Args>...>

MyStruct<X, Y> // expands to seq<pair<Other, X>, pair<Other, Y>>

However, as far as I can tell, all these pattern expansions require (and retain) an enclosing block. I'm looking to expand a pattern inline, like this:

template<typename... Args>
struct MyStruct : seq<???Other, Args???...>

MyStruct<X, Y> // expands to seq<Other, X, Other, Y>

Is there a way to achieve this effect?

CodePudding user response:

Tested with gcc 12:

#include <functional>
#include <tuple>
#include <type_traits>

template<typename ...> class seq;
class Other;

template<typename T> struct tuple_2_seq;

template<typename ...Args>
struct tuple_2_seq<std::tuple<std::reference_wrapper<Args>...>> {

    typedef seq<Args...> type;
};

template<typename ...Args> struct add_other
    : tuple_2_seq<decltype(
                  std::tuple_cat(std::declval<
                      std::tuple<std::reference_wrapper<Other>,
                         std::reference_wrapper<Args>>>()...)
              )> {};

static_assert( std::is_same_v< typename add_other<int, float>::type,
           seq<Other, int, Other, float>>);

So, with all of that in place you'll want to try your luck with

template<typename... Args>
   struct MyStruct : typename add_other<Args...>::type {
 // ...
}

In hindsight using a plain pointer instead of std::reference_wrapper would've also worked, but what's done is done.

CodePudding user response:

If you fancy doing meta-programming yourself, you can accomplish the behaviour with four utility overloads.

Like another answer pointed out, the key is concatenating seq types, so our utilities will do just that. The important thing to understand is that meta-programming is primarily functional in nature, so the tools will be recursion and pattern matching (all during overload resolution). Here are the overloads:

namespace detail {
    auto seq_concat() -> seq<>&;

    template<typename... Args>
    auto seq_concat(seq<Args...>&) -> seq<Args...>&;

    template<typename... Args, typename... Brgs>
    auto seq_concat(seq<Args...>&, seq<Brgs...>&) -> seq<Args..., Brgs...>&;

    template<class Seq, class... Seqs>
    auto seq_concat(Seq& s, Seqs&... ss) -> decltype(seq_concat(s, seq_concat(ss...)));
}

The first three are our "base case". When concatenating zero to two seqs, we lay out explicitly what type we should get, while the final overload is our general case. To concatenate a list of three or more "seq-like" types, is to concentrate the elements in the list tail, then take that result and concatenate it with the list head.

Now we can write the utility you need, because to create a seq<Other, A, Other, B> we may just concatenate seq<Other, A> with seq<Other, B>, and in if we need more types, we can do pack expansion on seq<Other, Args>... and concatenate all of those.

struct Other;
template<typename... Args>
using seq_interleave_with_other = typename std::remove_reference<decltype(detail::seq_concat(std::declval<seq<Other, Args>&>()...))>::type;

We create a pattern std::declval<seq<Other, Args>&>()... to "give us references to objects" we can use in an unevaluated context, then invoke detail::seq_concat(...) on the pattern. The return type is (almost) what we need, because our utilities added references for simplicity of implementing them. A quick trip through std::remove_reference and we are done. To use it, just write:

template<typename... Args>
struct MyStruct : seq_interleave_with_other<Args...>
{};

struct seq{}; template struct MyStruct : seq_interleave_with_other {}; int main() { } '),l:'5',n:'0',o:'C++ source #1',t:'0')),k:50,l:'4',n:'0',o:'',s:0,t:'0'),(g:!((h:executor,i:(argsPanelShown:'1',compilationPanelShown:'0',compiler:g493,compilerOutShown:'0',execArgs:'',execStdin:'',fontScale:14,fontUsePx:'0',j:1,lang:c++,libs:!(),options:'-std=c++11 -pedantic-errors -Wall -Wextra -Og',source:1,stdinPanelShown:'1',tree:'1',wrap:'1'),l:'5',n:'0',o:'Executor x86-64 gcc 4.9.3 (C++, Editor #1)',t:'0')),k:50,l:'4',n:'0',o:'',s:0,t:'0')),l:'2',n:'0',o:'',t:'0')),version:4" rel="nofollow noreferrer">Here's everything in a live example to play with.

  • Related