Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Expose template-template parameter of type

I have a type that depends on a template template parameter:

template<typename X_, template<typename, typename> class Y_>
struct A { /*...*/ };

which I construct with a factory function:

template<typename X_, template<typename, typename> class Y_>
A<X_, Y_> make() {
    return A<X_, Y_> { /*...*/ };
};

Now, I would like to add a factory function that takes an A by reference and assigns to it without me having to restate its template parameters:

template<typename A_>
void make(A_& a) {
    a = make<typename A_::X, typename A_::Y>();
}

I added two template aliases to A to achieve this:

template<typename X_, template<typename, typename> class Y_>
struct A { 
    using X = X_;
    template <typename... T>
    using Y = Y_<T...>;
    /* ... */ 
};

and then I try compiling:

A<int, std::vector> v;
make(v);

which yields, see Godbolt:

<source>: In instantiation of 'void make(A_&) [with A_ = A<int, std::vector>]':
<source>:24:11:   required from here
<source>:18:9: error: 'typename A<int, std::vector>::Y' names 'template<class ... T> using Y = class std::vector<T ...>', which is not a type

   18 |     a = make<typename A_::X, typename A_::Y>();

      |         ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

I do not understand why GCC 9.2 does not agree with me that Y is a type. How should I communicate my intensions to the compiler correctly?

like image 588
Tom Avatar asked Dec 06 '25 05:12

Tom


1 Answers

It is not typename but template you should use:

template<typename A_>
void make(A_& a) {
    a = make<typename A_::X, A_::template Y>();
}

In addition

template<typename X_, template<typename, typename> class Y_>
struct A { 
    using X = X_;
    template <typename... T>
    using Y = Y_<T...>;
    /* ... */ 
};

Y and Y_ are not equivalent, you need

template <typename T1, typename T2>
using Y = Y_<T1, T2>;

And I think it is only since C++17 they would be equivalent then.

Demo

like image 176
Jarod42 Avatar answered Dec 09 '25 01:12

Jarod42



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!