如何检查可变参数模板中的所有类型是否都可转换为size_t? [英] How to check that all types in variadic template are convertible to size_t?

查看:342
本文介绍了如何检查可变参数模板中的所有类型是否都可转换为size_t?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何检查可变模板声明中的所有类型都可以转换为size_t:

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
}

具有以下用法:

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 


b $ b

这里有类似的问题:
检查可变模板声明中的参数类型

推荐答案

> all_true trick from Columbo ,很简单:

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

在特定情况下,Check是一个构造函数:

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

这篇关于如何检查可变参数模板中的所有类型是否都可转换为size_t?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆