May someone tell me please why we do write size_t
after Graph
in the following line?
Graph<std::size_t> g;
Graph
is a class name and g
is an object. What does size_t
do there? Why should we write that?
I am so sorry if the question is too basic. But I could not find explanation on this and so far when I've wanted to create an object of class I have written:
class_name object;
like:
Graph g;
Because Graph
is a class template not an ordinary class.
Class templates define a class where the types of some of the variables, return types of methods, and/or parameters to the methods are specified as parameters.
Hence by using Graph<std::size_t > g;
you are using one of the class template instantiation which has size_t
as a type parameter.
You can use Graph<int > g
too and so on.
An addition:
When the compiler encounters template method definitions, it performs syntax checking ony, but doesn't actually compile the templates.
Let us write the template
template<typename T>
class MyClass
{
T memberVar{};
};
Only when the compiler encounters an instantiation of the template, such as MyClass<int> myObj
, it writes code for an int
version of the MYClass
template by replacing each T
in the class template definition with int
and so on.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.