How to check that all types in variadic template are convertible to size_t?

爷,独闯天下 提交于 2019-12-11 11:55:55

问题


How can I check that all types in a variadic 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 usage:

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 similar questions: Check for arguments type in a variadic template declaration


回答1:


With help from the really slick all_true trick from Columbo, it's a 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 where 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) {}


来源:https://stackoverflow.com/questions/31767645/how-to-check-that-all-types-in-variadic-template-are-convertible-to-size-t

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!