Does the compiler manage duplicate types generated with template meta-programming

71 views Asked by At

In the following code, I split a variadic template in two typeList's, the definition of typeList and putLeft are not important.

template<typename ...SL>
struct split {
    static const size_t size = sizeof...(SL);
    typedef typename putLeft<typeList<>,size/2, typeList<SL...>>::result firstHalf;
    typedef typename putLeft<typeList<>,size/2, typeList<SL...>>::rest secondHalf;
};

what I want to know is when I use putLeft<typeList<>,size/2, typeList<SL...>>::result and putLeft<typeList<>,size/2, typeList<SL...>>::rest later, does the compiler manage the duplicate struct that is putLeft<typeList<>,size/2, typeList<SL...>>::result, or does it compute the struct again ?

2

There are 2 answers

2
Barry On

Yes, the compiler will only instantiate putLeft<typeList<>,size/2, typeList<SL...>> once, at the point where you need the result type name.

However, it would probably be worth taking an alias to that so that you don't typo it on the second line:

template<typename ...SL>
struct split {
    static const size_t size = sizeof...(SL);
    using impl = putLeft<typeList<>,size/2, typeList<SL...>>;

    using firstHalf = typename impl::result;
    using secondHalf = typename impl::rest;
};

It won't have any effect on what actually happens, but readers of your code will thank you.

0
MSalters On

Modern compilers avoid recompilation. This helps keep compilation times down.

Older compilers recompiled the same type repeatedly, but that did not affect the correctness of the program. They just discarded duplicates in a later stage.