加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 如何获取模板的类型,如模板,以及检查T是int还是float或类

发布时间:2020-12-16 10:34:01 所属栏目:百科 来源:网络整理
导读:问题简述如下: template typename Tvoid 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);
问题简述如下:

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)?

解决方法

要打印int和float值,只需提供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'

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读