1#include <iostream>2#include <string>3template<classT>structS {4 S (T Arg) {5Std::cout << typeid (T). Name () <<Std::endl;6 }7 };8 9 intMain ()Ten { Ones<Const Char*> s{"Hello"};//deduced to S<std::string> A}
For the use of class templates, you need to specify template parameters. Since c++17, it is supported to deduce the type parameters of a class template based on the actual parameters of the constructor.
#include <iostream><string>Template<classstruct s { s (t arg) { << typeid (t). Name () << Std::endl; }}; int Main () { S s{"hello"// deduced to S<std::string >}
Users can also intervene in derivation by specifying a user-defined deduction guides
1#include <iostream>2#include <string>3template<classT>structS {4 S (T Arg) {5Std::cout << typeid (T). Name () <<Std::endl;6 }7 };8SChar Const*) S<STD::string>;9 intMain ()Ten { OneS s{"Hello"};//deduced to S<std::string> A}
Line 8th, which instructs the compiler to derive t as std::string when it encounters the char const* parameter
Reference: 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