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?
Parameter pack. (since C++11) sizeof... (C++11) A template parameter pack is a template parameter that accepts zero or more template arguments (non-types, types, or templates). A function parameter pack is a function parameter that accepts zero or more function arguments. A template with at least one parameter pack is called a variadic template .
A function parameter pack is a function parameter that accepts zero or more function arguments. A template with at least one parameter pack is called a variadic template . Template parameter pack (appears in alias template, class template, variable template and function template parameter lists) type ... Args(optional) typename|class ...
In a primary class template, the template parameter pack must be the final parameter in the template parameter list. In a function template, the template parameter pack may appear earlier in the list provided that all following parameters can be deduced from the function arguments, or have default arguments:
In general, if you are deploying a package using the package deployment model, you should use configurations instead of parameters. When you deploy a package that contains parameters using the package deployment model and then execute the package, the parameters are not called during execution.
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 */}
You could use fold expression in c++17 to do the same thing as other answers posted here but without the hassle of creating templates.
#include <type_traits>
template <typename... T, typename =
typename std::enable_if<
(true && ... && std::is_convertible_v<T, ___YOUR_TYPE___>),
void
>::type
>
constexpr auto foo(T...) noexcept {
// your code
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With