Checking type of parameter pack using enable_if
I think the simpler would be to use std::initializer_list
:
foo(std::initializer_list<double> args)
{
// Your stuff.
}
instead of variadic template.
It may require to use {}
instead of/ in addition to ()
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
}
And if you have access to C++20, you can use concepts
:
#include <type_traits>
template <typename... T>
requires(
(... && std::is_convertible_v<T, ___YOUR_TYPE___>)
)
constexpr auto foo(T...) noexcept {
// your code
}
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 */}
Here is another (c++11) version (heavily inspired by the T.C.'s one above):
#include <type_traits>
template <typename To, typename From, typename... R>
struct are_all_convertible {
constexpr static bool value = std::is_convertible<From,To>::value &&
are_all_convertible<To,R...>::value;
};
template <typename To, typename From>
struct are_all_convertible<To,From> {
constexpr static bool value = std::is_convertible<From,To>::value;
};
template<typename... T,
typename = typename std::enable_if<are_all_convertible<double, T...>::value>::type>
foo(T... t){ /* code here */}