banner



How To Implement A Template Class C++ Visual Studio

C++ Course Templates with Examples

Past , last updated September 22, 2019

In this tutorial we will cover class templates in C++ with simple examples.

What is a template in C++?

Templates in C++ are classes and functions that can operate with generic types. C++ template class tin be used for annihilation a regular class is able to do. The departure is that one course can take in many unlike data types. Grade templates are much like their sibling C++ template functions. Class templates e'er start their definition with a template keyword. Since there is no way to overload classes, its non permitted to take several classes with the same name, templated or regular.

C++ Template Class Example

A C++ class template starts with a template keyword and a number of arguments it can have. This is a definition of a grade template in C++.

                          // Form template Foo              template<typename              T>              class              Foo {};              // Course Bar              grade              Bar {};          

This is a completely legal Cpp Form Template. It doesn't do much, but when instantiating (using) the grade, y'all must specify the type. This is explicit template instantiation.

                          // Apply Foo with int and double, and Bar equally a regular class.              Foo<int> foo; Foo<double> foo_double; Bar bar;          

The proper noun of the template statement can exist well-nigh anything, and there tin can exist any number of template arguments. Though a class template with thousands of template arguments have a express usability.

How to use templates in C++

The Foo templated class above is not useful for anything. There are probably a few cases, merely I'yard non aware of any. Next up is to create a template, where the template argument is used for something.

                          template<typename              T>              class              Foo {              public:         T data; };          

In this Foo, the member information is exactly the type T. You can instantiate Foo<T> with int or double. You lot can fifty-fifty instantiate Foo with your own classes and/or structures. There is really no limit to what T will have. There are ways to limits what T will accept, but those techniques are reserved for more advanced chapters. All of these are legal instantiations of the Foo above.

            Foo<int>         foo1;              // Plain onetime data              Foo<double>      foo2;              // POD              Foo<std::string> foo3;              // Foo with a string              class              Bar {}; Foo<Bar> foo4;              // Foo with Bar              Foo<Foo<Bar>> foo5;              // Foo with a Foo with Bar                      

As you can see, templates are versatile and can exist used for many things, not simply regular data types such equally int or double. What you can do with a regular class, you can practice with a form template. But I did promise a real world example on class template.

Class Template with multiple parameters Case

Here's an example of a C++ Course Template with Constructor and several parameters:

                          template<typename              T,              typename              U,              typename              Westward>              class              MultiParameterTemplate {              public:     MultiParameterTemplate() =              default;              // default constructor              MultiParameterTemplate(T t, U u, Due west west) : m_t(t), m_u(u), m_w(due west) {};              private:     T    m_t;     U    m_u;     W    m_w; };              // Helper method              template<typename              T,              typename              U,              typename              West>              auto              make_multi_parameter_template(T && t, U && u, W && west) {              return              MultiParameterTemplate<T, U, Due west>(t, u, w); }              void              test_multiparameter() {              // Default constructor              MultiParameterTemplate<int, std::string, std::vector<int>> mpt;              // Will exist legal in the future              //auto mpt2 = MultiParameterTemplate(int(42), std::string("42"), std::vector<int>{42, 43, 44});              // Create with a helper method              auto              mpt3 = make_multi_parameter_template(int(42), std::cord("42"), std::vector<int>{42,              43,              44}); }          

Existent World Class Template Example

This class and code snippet volition be used to collect information, and when the data is collected, all information volition be sorted and printed. All the work is done by the form template, and there is only one implementation of the class. There is not an implementation specific for integral numbers or custom structs.

                          // Generic class sort              #include <vector>              #include <string>              #include <iostream>              template<typename              T>              form              generic_class_sort {              public:              void              add together(const              T &val) {             data.push_back(val);         }              void              add(const              std::initializer_list<T> & values)         {             data.insert(data.end(), values);         }              void              sort() {              // No predicate, use default predicate (std::less)              std::sort(information.begin(), information.end());         }              void              print() {              // Print all Ts              for              (const              T & t : information)             {                 std::cout << t <<              " ";             }              std::cout <<              "              \n              ";         }              individual:         std::vector<T> data; };              void              test_class_sort() {     generic_class_sort<int> ints;     ints.add together({              5,6,4,3,6,seven,2,1              });     ints.sort();     ints.impress();              // Output: 1 ii three 4 five half-dozen 6 vii              generic_class_sort<std::string> strings;     strings.add({              "e",              "a",              "d",              "c",              "f",              "b"              });     strings.sort();     strings.print();              // Output: a b c d east f              }          

Where to Apply Form Templates in C++

Class templates are used when some functionality tin't be independent into one office. Some notable examples are std::vector and std::list. Considering of class templates, it's possible to have blazon rubber containers. It also makes accidental mixing impossible. This lawmaking is illegal:

                          // Warning: Illegal code alee              #include <vector>              #include <cstdint>              std::vector<int32_t> ints; std::vector<int64_t> longs;  ints = longs;          

From this illegal program, both Microsoft Visual C++ and GCC will emit errors.

                          // Fault in Visual Studio              // Error C2679 binary '=': no operator found which takes a right-hand                            //   operand of type 'std::vector<int64_t,std::allocator<_Ty>>' '              //   (or there is no acceptable conversion)              // Fault in GCC:              // mistake: no match for 'operator='                            // (operand types are 'std::vector<int>' and 'std::vector<long int>')                      

Grade template specialization

Class template specialization is specialization of a class template. A notable example from the standard library is the assortment grade. std::array is a compile fourth dimension array of a blazon T with size Due north. It allocates an array on the stack and it has iterator support. It is more strongly typed than a regular C array and the size is a compile time constant. Information technology is hard to unintentionally innovate retention errors with std::array than the other assortment types.

The usage is std::assortment<int, 10> ten_ints;. The special case is when Northward is 0. When Due north is 0, all methods in std::array does zip, and the class itself volition non store anything, except for the minimum storage size of 1. All methods are empty and does cipher, and all methods returning some values, return default values. All of which volition be beautifully optimized away.

A template specialization of a form requires a primary class and a type or parameters to specialize.

                          // Master template course              template<typename              T>              grade              FooBar {              void              DoStuff(T t) {}      T data = T(); };          

A specialized template form behaves like a new class. There is no inheritance from the primary grade. It doesn't share anything with the principal template form, except the name. Any and all methods and members will have to exist implemented.

                          // Specialized template class for FooBar<int>              template<>              class              FooBar<int> { };          

With the instantiation:

            FooBar<double> foo_double; FooBar<int> foo_int;          

The compiler just sees the types FooBar<double> and FooBar<int> as two unlike types. The only mutual affair is the name. The compiler will look for the almost specific lucifer in the template lookup procedure. FooBar<int> matches exactly, and is selected.

Further reading: C++ Templates

C++ Templates Resource

Senior Software Engineer developing all kinds of stuff.

Comments

Y'all may apply these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <lawmaking> <del datetime=""> <em> <i> <q cite=""> <south> <strike> <strong>

Source: https://studiofreya.com/cpp/cpp-templates/cpp-class-templates-with-examples/

Posted by: enochsfark1980.blogspot.com

0 Response to "How To Implement A Template Class C++ Visual Studio"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel