微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

c – 如何静态检查模板的类型T是否为std :: vector,其中U为float,double或integral

如何检查参数包中的参数是否具有float,double,integral或其std :: vector的类型?

例如T = {int,long,std :: vector< double>}很好,

而T = {int,std :: vector< long double>}不是,因为我们不允许std :: vector为长双倍类型.

我有这么远

template<class ...T>
void foo(T... t)
{
    static_assert(std::is_same<float,T...>::value
               || std::is_same<double,T...>::value
               || std::is_integral<T...>::value
            /* || std::is_same<std::vector<float/double/integral>,T>::value ? */,"unsupported type!");
}

并不确定如何表达std :: vector的限制.

这将是一个很好的重用浮点/双精度/积分检查某种方式,所以我们不需要键入它们两次.就像是

bool basic_check = std::is_same<float,T...>::value
               || std::is_integral<T...>::value;

static_assert(basic_check
              || std::is_same<std::vector<basic_check>,T>,"unsupported type!");

当T = {}时,我也希望assert成功(即传递构建).

解决方法

您可以使用模板专业化创建自己的支票.我扩大了检查以包括long double,以减少代码的大小.
#include <type_traits>
#include <vector>

template<class T>
struct is_ok {
    static constexpr bool value =
        std::is_floating_point<T>::value ||
        std::is_integral<T>::value;
};

template<class T>
struct is_ok<std::vector<T>> {
    static constexpr bool value =
        std::is_floating_point<T>::value ||
        std::is_integral<T>::value;
};

这是一个演示:

#include <cstdio>
#define TEST(x) \
    std::printf("%s: %s\n",#x,is_ok<x>::value ? "true" : "false")

int main() {
    TEST(int);
    TEST(float);
    TEST(char *);
    TEST(std::vector<int>);
    TEST(std::vector<float>);
    TEST(std::vector<char *>);
    return 0;
}

输出

int: true
float: true
char *: false
std::vector<int>: true
std::vector<float>: true
std::vector<char *>: false

原文地址:https://www.jb51.cc/c/111764.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐