Reputation: 15
I have two function that returns a boolean value after comparing the two values that I am passing to the function. Now by question is how can we write a typedef using the following two functions to characterize them and define a new type?
functions:
bool compare1(float n1, float n2){
return n1<n2;
}
bool compare2(int n1, int n2){
return n1<n2;
}
Upvotes: 0
Views: 157
Reputation: 490158
I don't see a typedef doing much good here, but a template certainly could:
template <class T>
bool compare(T n1, T n2) {
return n1 < n2;
}
Note that this is pretty much the same as std::less<T>
already provides, except that std::less<T>
has specializations so it works with some types for which n1<n2
wouldn't necessarily give meaningful results. That means this exact case isn't very practical, but other cases of the general idea can be.
For the original case, you can't really use a typedef
. You can create a typedef
for the type of a pointer to one of the functions:
typedef bool (*ptr_func)(int, int);
But that still needs the parameter types specified, so you can't use it to refer to both functions that takes int
parameters and functions that take float
parameters. You can create a typedef
for a pointer to a function that takes a variadic argument list, but even though such a function could take either int
or float
parameters, that pointer wouldn't be the right type to refer to either of the functions you've given.
Upvotes: 3
Reputation: 48467
If you really really want to have an alias (aka typedef), then here it is:
bool compare1(float n1, float n2){
return n1<n2;
}
bool compare2(int n1, int n2){
return n1<n2;
}
template <typename T>
using Alias = bool(*)(T,T);
int main()
{
Alias<float> a = compare1;
std::cout << a(3.14f, 5.12f) << std::endl;
Alias<int> b = compare2;
std::cout << b(1, 2) << std::endl;
}
Upvotes: 2
Reputation: 41301
Probably you want to do something like this:
template<typename T>
bool compare(T n1, T n2){
return n1 < n2;
}
Upvotes: 1