Suppose we have a class:
template <class Type>
class A
{
public:
void function1(float a, Type b);
void function1(float a, float b);
};
Now instantiate the class like this:
A<int> a;
It's fine, this class will have 2 overloaded functions with these parameters: (float a, int b); (float a, float b);
But when you instantiate the class like this:
A<float> a;
You get compile error:
member function redeclared.
So, depending on the type of Type, I wan't (or don't want) the compiler to define a function, something like this:
template <class Type>
class A
{
public:
void function1(float a, Type b);
#if Type != float
void function1(float a, float b);
#endif
};
But, of course, the syntax above doesn't work. Is it possible to perform such a task in C++? If possible, please provide an example.
Defining a Function TemplateA function template starts with the keyword template followed by template parameter(s) inside <> which is followed by the function definition. In the above code, T is a template argument that accepts different data types ( int , float , etc.), and typename is a keyword.
A template parameter is a special kind of parameter that can be used to pass a type as argument: just like regular function parameters can be used to pass values to a function, template parameters allow to pass also types to a function.
For normal code, you would use a class template when you want to create a class that is parameterised by a type, and a function template when you want to create a function that can operate on many different types.
Template friendsBoth function template and class template declarations may appear with the friend specifier in any non-local class or class template (although only function templates may be defined within the class or class template that is granting friendship).
You can use some C++11
std::enable_if
:
template <class Type>
class A
{
public:
template<typename t = Type,
typename std::enable_if<!std::is_same<t, float>::value, int>::type = 0>
void function1(float a, Type b) {
}
void function1(float a, float b) {
}
};
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