码迷,mamicode.com
首页 > 编程语言 > 详细

C++ class template argument deduction

时间:2018-04-06 20:24:38      阅读:228      评论:0      收藏:0      [点我收藏+]

标签:指定模板参数   cpp   参考   body   and   span   template   temp   .com   

 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

C++ class template argument deduction

标签:指定模板参数   cpp   参考   body   and   span   template   temp   .com   

原文地址:https://www.cnblogs.com/thomas76/p/8728604.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!