栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

c++ 模板 特化与偏特化

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

c++ 模板 特化与偏特化

文章目录
    • 内容提炼
    • 代码一(内置类型)typename
    • 代码二(自定义类型) class
    • 注意点

内容提炼
  • decltype(expression) 关键字:得出experssion的类型
  • typeid(variable) 返回variable的类型
  • auto + + ->decltype{} 自动推演返回值
  • 特化与偏特化
代码一(内置类型)typename
#include
using namespace std;
//auto +  + ->decltype{} 自动推演返回值
template 
auto add(T a,U b)->decltype(a+b){
    return a + b;
}

//特化1:T和U都是位置的,但是针对泛型幽默中特征,(都是指针量输入)
template 
auto add(T* a,U* b)->decltype(*a+*b){
    return *a + *b;
}

//特化2: 全特化:针对某一个具体情况
template <>
int add(int a,int b){
    return a+b;
}

int main(){
    int a,b;
    double m,n;
    cout << "33[33mplease input a(int),b(int),m(double),n(double) : 33[0m"<> a >> b >> m >> n;
    cout << typeid(a+b).name() << endl;
    cout << "33[32madd("< 

结果为:

please input a(int),b(int),m(double),n(double) : 
3 5 7.8 3.4
i
add(3,5) = 8
d
add(3,7.8) = 10.8
d
add(3,3.4) = 6.4
i
add(0x7ffc93c9b080,0x7ffc93c9b084) = 8

代码二(自定义类型) class
#include "head.h"

using namespace std;

template  
class Test{
public:
    Test(){
        cout << "normal template" << endl;
    }
};

template  //偏特化
class Test{
public:
    Test(){
        cout << "partial specialization template" << endl;
    }
};

template <> //特化
class Test{
public:
    Test(){
        cout << "specialization template" << endl;
    }
};

int main(){
    Test t1;
    Test t2;
    Test t3;
    Test t4;
    Test<> t5; //T和U默认分别为double,double。
    return 0;
}

结果为:

specialization template
normal template
partial specialization template
normal template
normal template
注意点

内置类型的模板参数是作为函数体的类型参数去使用,它的特化在于对参数的具象化。
自定义类型的模板的偏特化就需要在调用它是做显示声名。在定义该模板类时也需要对特化的类型做

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/873451.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号