How to check that all types in a variation template are converted to size_t?

How can I verify that all types in a variational template declaration can be converted to 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
}

With the following use:

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 

Here are some similar questions: Check the type of arguments in a variational template declaration

0
source share
1 answer

With a really subtle trick all_truefrom Columbo , this is a light breeze:

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) {}

Live on coliru

And in the specific case when Check is a constructor:

template<typename... Args, class = std::enable_if_t<all_true<std::is_convertible<Args, std::size_t>{}...>{}>>
    explicit Check(Args... args) {}
+4
source

Source: https://habr.com/ru/post/1621653/


All Articles