6

Using the model in class

 3 years ago
source link: https://www.codesd.com/item/using-the-model-in-class.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Using the model in class

advertisements

I am new to C++, and my question may seem simple. I can't understand these codes:

template<typename a, typename b>
bool operator < (const Pair<a,b> &op1 , const Pair<a,b> &op2)
{
    return (op1.first() < op2.first())
};

It seems that operator is a function and its output type is bool. So what is that "template" for? Because this template has been defined before class definition.

     template<typename a, typename b>
     class Pair { ...


So what is that "template" for? - well in that case, it is used to pass a dynamic type parameter to '<' operator, that is basically the use of templates, so that you can declare your class/method only once in yet you can pass different data types to it. In your case, if you don't use template, then you probably would create overloaded methods for each data type that your '<' operator would want to process.

BTW: operator is not a function, it's a keyword for overloading an operator, in this case '<' less than.

Tags templates

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK