C++ class template argument deduction

 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

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍;

也有高质量的技术群,里面有嵌入式、搜广推等BAT大佬

    C++ class template argument deduction

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/397498

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年4月11日 上午9:13
下一篇 2023年4月11日 上午9:13

相关推荐