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

posted @ 2018-04-06 19:29  thomas76  阅读(368)  评论(0编辑  收藏  举报