Search code examples
c++templateslanguage-lawyervariadic-templatestemplate-argument-deduction

g++ and clang++ are both bugged with template function parameter pack expansion?


This is a follows up of another question where an answer point my attention to Templates [temp.param] 17.1.17 (last C++17 draft, but I suppose also preceding standardizations) where is stated that

A template parameter pack that is a pack expansion shall not expand a parameter pack declared in the same template-parameter-list.

with an example of this limitation

template <class... T, T... Values> // error: Values expands template type parameter
struct static_array;               // pack T within the same template parameter list

So, if I understand correctly this rule, the following function (that I find extremely reasonable) is illegal

template <typename ... Types, Types ... Values>
void foo (std::integral_constant<Types, Values>...)
 { ((std::cout << Values << std::endl), ...); }

because the second parameter pack (Types ... Values) expand a parameter pack (Types) declared in the same template parameter lists.

Anyway, both g++ (9.2.0, by example) and clang++ (8.0.0, by example) compile the following code without problem

#include <iostream>
#include <type_traits>

template <typename ... Types, Types ... Values>
void foo (std::integral_constant<Types, Values>...)
 { ((std::cout << Values << std::endl), ...); }

int main()
 {
   foo(std::integral_constant<int, 0>{},
       std::integral_constant<long, 1L>{},
       std::integral_constant<long long, 2LL>{});
 }

So I suppose there is something I misunderstand.

Are both g++ and clang++ bugged or am I that misunderstand the standard?


Solution

  • It's illegal, the standard is very clear. For what it's worth, MSVC doesn't seem to accept the code (https://godbolt.org/z/DtLJg5). This is a GCC bug and a Clang bug. (I didn't check old versions.)

    As a workaround, you can do something like this:

    template <typename... ICs>
    std::enable_if_t<std::conjunction_v<is_integral_constant<ICs>...>> foo(ICs...)
    {
        ((std::cout << ICs::value << '\n'), ...);
    }
    

    Live demo