C++ class template argument deduction

本文介绍C++17中新增的类模板参数推导功能,展示如何利用构造函数参数自动推导模板类型,并通过用户定义的推导指南增强这一特性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 1 #include <iostream>
 2 #include <string>
 3 template<class T> struct S { 
 4     S(T arg) {
 5         std::cout << typeid(T).name() << std::endl;
 6     }
 7 };
 8 
 9 int main()
10 {
11     S<const char*> s{"hello"}; // deduced to S<std::string>
12 }

类模板的使用,需要指定模板参数。自从C++17起,支持根据构造函数的实际参数,推导类模板的类型参数。

#include <iostream>
#include <string>
template<class T> struct S { 
    S(T arg) {
        std::cout << typeid(T).name() << std::endl;
    }
};

int main()
{
    S s{"hello"}; // deduced to S<std::string>
}

用户还能干预推导,通过指定一个User-defined deduction guides

 1 #include <iostream>
 2 #include <string>
 3 template<class T> struct S { 
 4     S(T arg) {
 5         std::cout << typeid(T).name() << std::endl;
 6     }
 7 };
 8 S(char const*) -> S<std::string>;
 9 int main()
10 {
11     S s{"hello"}; // deduced to S<std::string>
12 }

第8行,指示编译器,当遇到char const*参数时,就把T推导成std::string
参考:http://en.cppreference.com/w/cpp/language/class_template_argument_deduction
https://stackoverflow.com/questions/40951697/what-are-template-deduction-guides-and-when-should-we-use-them

转载于:https://www.cnblogs.com/thomas76/p/8728604.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值