I am trying to understand a piece of code of C++11.
A class contains 2 functions as shown below:
class abc
{
public:
void integerA(int x);
template<typename typ>
void integerA(typ x);
};
I am unable to understand benefit of declaring 2 same functions. Why not declare only one template function?
Only one benefit I can assume is we know int data type which can be passed to this function. This might be little faster. But for this, do we really need to create a separate function with int data type?
The main reason to do something like this is to specialize void integerA(int x) to do something else. That is, if the programmer provides as input argument an int to member function abc::integerA then because of the C++ rules instead of instantiating the template member function the compiler would pick void integerA(int x) because concrete functions are preferred when possible instead of instantiating a template version.
A more straightforward way to do this would be to specialize the template member function in the following manner:
class abc
{
public:
template<typename typ>
void integerA(typ x);
};
template<typename typ>
void abc::integerA(typ x) {
...
}
template<>
void abc::integerA(int x) {
...
}
LIVE DEMO
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With