C + + class template argument deduction

Source: Internet
Author: User

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&LT;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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.