C++ class template argument deduction

 1 #include 
 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
12 }

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

#include 
#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
}

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

 1 #include 
 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*) -> Sstring>;
 9 int main()
10 {
11     S s{"hello"}; // deduced to S
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

你可能感兴趣的:(C++ class template argument deduction)