如何获取模板的类型,如模板<类型名 T>,并检查 T 是 int 还是浮点数或类

How to get the type of a template, like template <typename T>, and to check if T is int or float or a class

本文关键字:类型 检查 int 浮点数 lt 何获取 获取 gt      更新时间:2023-10-16
问题

简要描述如下:

template <typename T>
void display(T data){
    if(is_int(T)) // how to check if T is int in this function is_int
        printf("<int> %d", data);
    if(is_float(T)) // how to check if T is float in this function is_float
        printf("<int> %f", data);
    if(is_class(T)) // how to check if T is class in this function is_class
        data.display();
}

这里假设 T 可以是 int 的类型、float 或类的类型。

如果我定义了一些变量并想使用相同的函数显示它们的值:

int a = 10:
float b = 2.7;
A_Class c;
display(a);
display(b);
display(c);
display(new int(3));
display(new float(1.899));
display(new float(1));

我知道在C++中,有一种检查int和float的解决方案(仅用于打印问题),即使用std::cout,如此问题中所述(C++模板 - 如何查找模板类型是基本类型还是类)。

使用 std::is_integral::value 不适用于以下情况:

display(new int(3));
display(new float(1.899));
display(new float(1));

因为这些变量是类而不是基本类型。那么对于这种情况,我们如何判断新int(),new float()的类型(int或float)?

要打印intfloat值,只需分别提供采用这些类型参数的display()重载。对于包含名为 display() 的成员函数的对象,可以使用 SFINAE 有选择地启用 display() 的自由函数形式

#include <iostream>
#include <type_traits>
template<typename T>
auto display(T const& t) -> decltype(t.display(), void())
{
    std::cout << "display(T const& t)n";
}
void display(int)
{
    std::cout << "display(int)n";
}
void display(double)
{
    std::cout << "display(double)n";
}
struct foo
{
    void display() const
    {
        std::cout << "foo::displayn";
    }
};
struct bar {};
int main()
{
    display(10);
    display(10.0);
    display(foo());
//    display(bar()); // doesn't compile
}

现场演示当您打电话给display(bar());时会发生什么

main.cpp:35:18: error: no matching function for call to 'display(bar)'
     display(bar()); // doesn't compile
...
main.cpp:5:49: error: 'const struct bar' has no member named 'display'

您直接提供版本,检查由<type_traits>提供:

template <typename T>
typename std::enable_if<std::is_same<T, int>::value>::type
display(T data){
    printf("<int> %d", data);
}
template <typename T>
typename std::enable_if<std::is_same<T, float>::value>::type
display(T data){
    printf("<int> %f", data);
}
template <typename T>
typename std::enable_if<std::is_class<T>::value>::type
display(const T& data){ // you probably don't want to copy the argument
    data.display();
}

实现的一种方法是使用数字限制。但是,这是为了检查它是整数还是浮点数。

您可以执行以下操作:

#include<limits>
template <typename T>
void display(T data){
  if(std::numeric_limits<T>::is_signed) // how to check if T is int in this function is_int
     printf("<int> %d", data);
  else // how to check if T is float in this function is_float
     printf("<int> %f", data);
}