Search code examples
c++templatesvariadic-templates

Checking type of parameter pack using enable_if


Since there is a restriction on allowed non-type variadic templates, I am trying to write a function taking an arbitrary number of doubles using enable_if. In essence, I want to do something like:

    template<typename... T,
    typename = typename std::enable_if<std::is_convertible<T, double>::value, T>::type>
    foo(T... t){ /* code here */ }

I'm opting to put the enable_if as a default value for an unnamed parameter since my function is actually a constructor and will not have a return value. This would work for a single parameter, but as it's a variadic template T is a parameter pack, and the above code is not valid. So, how can I check every parameter is convertible to a double?


Solution

  • The bool_pack trick again.

    template<bool...> struct bool_pack;
    template<bool... bs> 
    using all_true = std::is_same<bool_pack<bs..., true>, bool_pack<true, bs...>>;
    

    Then

    template<class R, class... Ts>
    using are_all_convertible = all_true<std::is_convertible<Ts, R>::value...>;
    

    and finally

    template<typename... T,
    typename = typename enable_if<are_all_convertible<double, T...>::value>::type>
    foo(T... t){ /* code here */}