Same function with and without template
I am trying to understand a piece of C ++ 11 code.
The class contains 2 functions as shown below:
class abc
{
public:
void integerA(int x);
template<typename typ>
void integerA(typ x);
};
I can't figure out the benefits of declaring two functions that are the same. Why not just declare one template function?
The only advantage I can assume is knowing the data type int
that can be passed to this function. It might be a little faster. But for this we really need to create a separate function with a data type int
?
source to share
The main reason to do something like this is to specialize void integerA(int x)
in order to do something else. That is, if a programmer provides as an input argument int
for a member function abc::integerA
, then due to C ++ rules, instead of instantiating a template member function, the compiler chooses void integerA(int x)
because specific functions are preferred whenever possible over instantiating a template version.
An easier way to do this is to specialize the template member function like this:
class abc
{
public:
template<typename typ>
void integerA(typ x);
};
template<typename typ>
void abc::integerA(typ x) {
...
}
template<>
void abc::integerA(int x) {
...
}
source to share