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起,支持根據構造函數的實際參數,推導類模板的類型參數。ios

#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 guideside

 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函數

相關文章
相關標籤/搜索