简体   繁体   中英

Template class member function

I have a class called Time . There are only two private members: int hours and int minutes . The public access specifier only contains functions like adding, subtracting etc.

But there's a particular function which doesn't behave the way I want. It's declared public in the class.

This way it compiles:

Time Time::operator*(const int &mult)
{
   minutes = minutes*mult;
   hours = hours*mult + minutes/60;
   minutes %= 60;
   return *this;
}

But what if the argument isn't na int , but a float , or double ? I suppose using templates is the best option, rather than overloading the function:

template <class T> Time Time::operator*(const T &mult)
{
   minutes = int(minutes*mult);
   hours = int(hours*mult) + minutes/60;
   minutes %= 60;
   return *this;
}

However, writing it this way gives a compile error:

error LNK2019: unresolved external symbol "public: class Time __thiscall Time::operator*<int>(int const &) " (??$?DH@Time@@QBE?AV0@ABH@Z) referenced in function _main

It means that I can't use operator overloading with templates or what?

Thank you
Robert

Templates are like patterns for a function. They have to be instantiated before you use them. For your example, you need an instantiation for Time::operator* with T=int, which is obtained by substituting each T in your function with int .

There are two ways this instantiation can happen:

First, there is explicit instantiation , where you have to instantiate the template for all types you want to use it on. An explicit instantiation for your operator* for T=int looks like this:

template Time Time::operator*<int>(const int &mult);

The compiler needs to see the definition to instantiate a template, so here the templated function's implementation must be in the same file or in an included file, but you can put the explicit instantiations together with the implementation of the template in an implementation file.

Another way is implicit instantiation , where the templates get instantiated on the caller side, when they are used. For this method, the template implementation must be visible when you use the template. The easiest way to achieve this is to put the template implementation in the header file where the template is declared.

So you have two choices, either add an explicit instantiation for int to the implementation file or move the template implementation to the header file.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM