首页 文章

如何获取模板的类型,如模板<typename T>,并检查T是int还是float或类

提问于
浏览
3

问题简述如下:

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++ templates - How to find whether the template type is a basic type or a class)中所述 .

使用std :: is_integral :: value不适用于这样的情况:

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

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

3 回答

  • 2

    要打印 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::display\n";
        }
    };
    
    struct bar {};
    
    int main()
    {
        display(10);
        display(10.0);
        display(foo());
    //    display(bar()); // doesn't compile
    }
    

    Live demo当您致电 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'
    
  • 4

    您直接提供版本,检查由<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();
    }
    
  • 7

    实现的一种方法是使用numeric limits . 但是,这是检查它是整数还是浮点数 .

    您可以执行以下操作:

    #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);
    }
    

相关问题