Loki MakeTypelist recursive template make me confuse

Recursive template will terminate due to specialization template<> struct MakeTypelist<> being defined which returns NullType value of Result.

This specialization is totally equal to next variant of code

template<>
struct MakeTypelist<NullType, NullType, NullType, NullType, ..... /* ... 18 Times ... */>
// .......

Because if not all or none template params are provided then all non-provided template params are considered to be equal to default values i.e. to = NullType (see main template definition, it has all 18 arguments-types having default = NullType).

This choosing of default arguments for those template params that are not provided has same logic like in using functions with default arguments, e.g. if you have function like void f(int a = 0, int b = 0) then you may call it three different ways f() and f(0) and f(0, 0) and all will give same results. And those function arguments that are not provided will be taken equal to defaults. Same is here in template specialization – if you don’t provide any arguments i.e. write struct MakeTuplelist<> then all 18 arguments-types will be considered to be NullType because all 18 arguments have defaults = NullType, same behaviour like in function with default arguments example above.

Also in specialization you may provide just some of template arguments, the rest will be considered to be equal to defaults, e.g. template<> struct MakeTypelist<int, bool> specialization will be totally same as specialization template<> struct MakeTypelist<int, bool, NullType, NullType, ...... /* 16 NullTypes */>.

And recursion terminates because very last tail is equal to MakeTypelist<NullType, NullType, NullType, .....> which matches specialized version of MakeTypelist which cuts recursion by providing NullType value for Result.

Try it online!

PS. Same defaults-behavior is applied not only to specialization of template, but also to usage, you may use template like typedef MakeTypelist<> T; or typedef MakeTypelist<int, bool> T; in both cases the rest of 18 template arguments-types will become equal to defaults = NullType.

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top