How to avoid this kind of code repetition?
Asked Answered
G

1

6

In order to avoid code repetition, I need to do something like this (in my real code I have much more complex types similar to T1 and T2):

template <class T1, class T2>
struct A 
{};

template <class T1, class T2>
struct B 
{};

template <class X>
struct C 
{
   using p1 = int;
   using p2 = char;

   using some = X<p1, p2>;
};

int main()
{
   C<A> o1; // must produce C<A<int,char> >
   C<B> o2; // must produce C<B<int,char> >
}
Glyph answered 3/8, 2020 at 20:1 Comment(2)
Is that supposed to be C<A>::some o1; and C<B>::some o2;?Ectoblast
typo fixed now is OKGlyph
Y
13

Your class C needs to use a template template parameter in order to accept A and B as input to its own template so it can then pass parameters to them, eg:

template <template<typename T1, typename T2> class X>
struct C 
{
   using p1 = int;
   using p2 = char;

   using some = X<p1, p2>;
};

Now you can do this:

C<A> o1; // produce C<A<int,char> >
C<B> o2; // produce C<B<int,char> >

See a demo

Yahairayahata answered 3/8, 2020 at 20:5 Comment(2)
Wow... Is that standard feature?Glyph
@Glyph Yes indeed, and here more read from stdYahairayahata

© 2022 - 2024 — McMap. All rights reserved.