如何检查可变参数模板声明中的所有类型是否都可以转换为size_t:
// instantiate only if extents params are all convertible to size_t
template<typename T, size_t N>
template<typename... E>
Array<T,N>::Array(E... extents) {
constexpr size_t n = sizeof...(extents);
static_assert(n == N, "Dimensions do not match");
// code for handling variadic template parameters corresponding to dimension sizes
}
具有以下用途:
Array<double, 2> a(5,6); // OK 2-D array of 5*6 values of doubles.
Array<int, 3> a(2,10,15) // OK 3-D array of 2*10*15 values of int.
Array<int, 2> a(2, "d") // Error: "d" is not a valid dimension and cannot be implicitly converted to size_t
以下是类似的问题: Check for arguments type in a variadic template declaration
答案 0 :(得分:4)
借助Columbo中非常流畅的all_true
技巧,您可以轻而易举地实现这一目标:
template <bool...> struct bool_pack;
template <bool... v>
using all_true = std::is_same<bool_pack<true, v...>, bool_pack<v..., true>>;
template <class... Args>
std::enable_if_t<
all_true<std::is_convertible<Args, std::size_t>{}...>{}
> check(Args... args) {}
在Check是构造函数的特定情况下:
template<typename... Args, class = std::enable_if_t<all_true<std::is_convertible<Args, std::size_t>{}...>{}>>
explicit Check(Args... args) {}