Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ template template infer type arguments

Tags:

c++

templates

I have a base type

template<int p> 
struct Base {};

and a more complex stuff built upon many versions of Base (some are int-templates, some are class-templates):

template<template<auto inner> typename basetype, typename p, typename q>
struct Complex {};

Then, i create variable like that :

Complex<Base, Base<1>, Base<2>> c;

is there a way to infer my first template parameter is Base, or that p and q are specialized version of basetypeso I could write

Complex<Base<1>, Base<2>> c;

I guess there isn't. But templates hide some magic sometimes.

like image 680
Regis Portalez Avatar asked Jan 01 '23 23:01

Regis Portalez


1 Answers

If you want Complex to always have its two arguments be specializations of the same template, then you can achieve this using partial specialization:

// the primary template remains incomplete, so most uses of it will be an error
template <class T, class U> struct Complex;

template <template<auto> typename basetype, auto p_arg, auto q_arg>
struct Complex<basetype<p_arg>, basetype<q_arg>> {
    // ...
};

When you instantiate Complex<Base<1>, Base<2>>, the arguments basetype, p_arg, and q_arg will be deduced as Base, 1, and 2, respectively.

like image 124
Brian Bi Avatar answered Jan 09 '23 07:01

Brian Bi