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

相关文章

本程序的编译和运行环境如下(如果有运行方面的问题欢迎在评...
水了一学期的院选修,万万没想到期末考试还有比较硬核的编程...
补充一下,先前文章末尾给出的下载链接的完整代码含有部分C&...
思路如标题所说采用模N取余法,难点是这个除法过程如何实现。...
本篇博客有更新!!!更新后效果图如下: 文章末尾的完整代码...
刚开始学习模块化程序设计时,估计大家都被形参和实参搞迷糊...