You have learned class and template class from previous days. (day-15: c++ template)
On day-15, I used template class to introduce template,
In most cases, class template is more accurate than template class.
Dialectics: what's the difference between them ? Why do we inverse the order by using class template ?
Let's think about some questions,
So then, we will call the template class class template, because it is template, used for creating classes.
Got:
class template
template <typename type_t00> class my_class { };
On day-15, we have learned the template parameter is a type.
However, the template parameter (and argument) can be a value:
template <int value_v00> class my_class { };
value_v00 is not a type, it is a value,
How to instantiate it:
my_class<23> object1; auto object2 = my_class<32>{};
The non-type template parameter is called c++ nttp.
#include <iostream> template <int value_v00> class my_class { public: void print() const {std::cout << value_v00 << std::endl;} }; int main() { auto obj3 = my_class<32>{}; obj3.print(); }
If A is derived from B, both A and B can be a class template, or a class (non-template).
#include <iotream> template <typename type_t00> class B { }; template <typename type_t00> class A: public B<type_t00> // A is derived from B { }; int main() { A<int> obj1; auto obj2 = A<float>{}; }
A<int>
You pass the template type parameter int to A, A will pass the template parameter int to B .
A passes a template parameter to B, can A pass A itself to B? Absolutely, it can.
template <typename type_t00> class B {}; template <typename type_t00> class A: public B<A<type_t00>> { };
Using the derived class as the template argument of the base class is a c++ idiom, it is called CRTP, coined by Jim Coplien in 1995.
template <typename type_t00> class base_class {}; class derived_class: public base_class<derived_class> {};
You pass paramter to A, A is derived from B, ...
Is it possible that A is derived from its parameters ? Yes !
#include <iostream> template <typename type_t00> class A: public type_t00 { }; class B { }; int main() { auto obj2 = A<B>{}; }
Multiple parameters work too:
#include <iostream> template <typename type_t00, typename type_t01, typename type_t02> class A: public type_t00, public type_t01, public type_t02 { }; class B {}; template <typename type_t00> class C {}; class D {}; int main() { auto obj1 = A<B, C<int>, D>{}; }
Written on Nov 13, 2024
c++ std::exception:
std::cout.write(err.data(), err.size());
std::cout << std::endl;
caught:
=================================== # The c++ programming language. # # # # Join c++ Discord: yZcauUAUyC # # Deck # ===================================