Templates and generics programming

Source: Internet
Author: User

For the first time, look at the first section.

1. Instead of defining a function for each type, we can define a template for the function.

Comparison function:

  1. #include <iostream>
  2. Template <TypeName t>
  3. int compare (const T&V1, const T&V2)
  4. {
  5. if (V1 < v2)
  6. return-1;
  7. if (V1 > V2)
  8. return 1;
  9. return 0;
  10. }
  11. int main ()
  12. {
  13. int i1 = ten, i2 = 20;
  14. double D1 = 20.1, d2 = 20.01;
  15. unsigned u1 = ten, U2 = 10;
  16. Std::cout << Compare (I1, i2) << Std::endl;
  17. Std::cout << Compare (D1, D2) << Std::endl;
  18. Std::cout << Compare (U1, U2) << Std::endl;
  19. }

Template definitions start with the keyword templates,

followed by a list of parameters, which is a comma-delimited list of one or more template parameters, surrounded by < >.

When we invoke a function template, the compiler uses the arguments of the function to infer the template arguments for us

2. Type parameters

You must use the keyword class or typename before the type parameter

In the template parameter list, these two keywords have the same meaning and can be used interchangeably, and the two keywords can be used together in a template parameter list

The type parameter is used in the function we can use it as a normal type, such as the parameters of the function, the return value, and the definition of variables inside the function, etc.

3. Non-type template parameters

In addition to defining type parameters, we can also define non-type parameters, which represent a value rather than a type, and we specify it by a specific type name rather than by the keyword class or typename.

When a template is instantiated, the non-type parameter is replaced by a compiler-inferred value.

A non-type parameter can be a shape, or a pointer to an object or function type, or (lvalue) reference, bound to a non-type shape parameter must be a constant, bound to a pointer or a reference to a non-type template

Arguments must have a static lifetime for the argument's arguments.

Note: Templates for non-type template parameters must be constant expressions

Inline and constexpr can also be decorated with function templates, placed in front of the return value

4. Writing type-independent code

Two important principles for writing generic code

<1. A function parameter in a template is a const reference

<2. Use < comparison only in function body condition

These two can reduce the requirements for the type

For example, a const reference guarantees that the function can be used for types that cannot be copied.

< comparisons can be used for most types that define < comparisons.

Conclusion: The template program should minimize the requirement of the actual parameter type

5. Template compilation

Template compilation differs from normal compilation in that the compiler generates code when using instantiation, and in order to generate an instantiated version, the compiler needs to master the definition of a function template or class template member function.

Therefore, unlike non-template code, a template's header file usually includes both a declaration and a definition.

The designer of the template should provide a header file that contains the template definition and declarations of all the names used in the class template or member definition.

The user of the template must contain the header file of the template, as well as any type of header file used to instantiate the template.

6. Most compilation errors are reported during instantiation

It is the responsibility of the caller to ensure that the arguments that are passed to the template support the actions required by the template, and that these actions work correctly in the template.

Example: writing a template that behaves like a find algorithm requires two template type parameters, an iterator parameter representing a function, and another type that represents a value.

  1. #include <iostream>
  2. #include <string>
  3. #include <list>
  4. #include <vector>
  5. template<TypeName Iterator, TypeName t>
  6. Iterator Find (const iterator &beg, const iterator &end, const t&ele)
  7. {
  8. For (Auto it = beg; it! = end; ++it)
  9. {
  10. if (*it = = ele)
  11. return it;
  12. }
  13. return end;
  14. }
  15. int main ()
  16. {
  17. std::vector<int>ivec1 = {1,2,3,4,5,6,7,8,9,0};
  18. Auto ret = Find (Begin (IVEC1), End (IVEC1), 3);
  19. if (ret = = End (IVEC1))
  20. Std::cout << "not find" << Std::endl;
  21. Else
  22. Std::cout << "Find" << *ret << Std::endl;
  23. Std::list<std::string>il = {"111","222", "333","444","555"};
  24. Auto Ret2 = Find (Il.begin (), Il.end (), "333");
  25. if (Ret2 = = Il.end ())
  26. Std::cout << "not find" << Std::endl;
  27. Else
  28. Std::cout << "Find" << *ret2 << Std::endl;
  29. }

2. Class templates

1. Each instance of a class template forms a separate class, but there is no relationship between the class and the class.

<2. We can either define member functions for them outside of the class template, or we can define them inside the class template, and the inner definition is implicitly declared as a restrained function.

<3. A member function of a class template has the same template parameters as the template, so a member function defined outside the template must start with the keyword template followed by a parameter list.

<4. By default, for an instantiated class template, its members are instantiated only when they are used.

<5. When we use a class template type, we must provide a template parameter, but with one exception, in the class template's own scope, we can use the template name directly without providing the argument.

Template class and friend

<6. Whether the class and friends are separate templates is irrelevant. Friend relationships are scoped to be instantiated with the same type.

<7. A template class can also specify another template class as a friend or a specific instance of another template class

<9. Class template Aliases (c++11)

In the old standard, we can only use TypeDef to define type aliases for specific template types.

In the C++11 standard, we can define a template type alias for a template class, and multiple parameters can specify that the parameter is T or a specific type.

Template <TypeName T, TypeName X, TypeName z> using TEP = C<t, X, z>;

tep<int, int, int> t;

<10. Static members of class templates

When a class template contains static members (data or functions), each instance of a class template has a static member, and when you define a static member of a class template, you must precede it with a template < parameter list >

3. Template parameters

<1. Template parameters and scopes

Template parameters conform to hidden rules, and a template parameter name can appear only once in the parameter list.

The declaration of all the templates required for a particular file is usually placed together at the beginning of the file, before any code that uses these templates.

<2. Using type members of a class

When we work with templates, we have to let the compiler know if the name represents a type

Attention:

Remember that TypeName and class are not identical and must be used in cases where a type is specified rather than a name TypeName

For example typedef typename T::SIZE_TYPE = Size_type

Source: http://blog.csdn.net/wwh578867817/article/details/43306513

Templates and generics programming

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.