|
-
July 29th, 2013, 06:56 AM
#5
Re: Determine the type in the function template
As above pointed out, this is going somewhat against the reason of templates, which means you have code that will generically work for any type of template parameter you pass in.
But yes, there are cases where you will want to alter how something works for some types, and this is called specialisation (or partial specialisation)
Code:
// Generic code, adds a and b
template <class myType>
myType Function(myType a, myType b)
{
return a+b;
}
// specialisation for int subtracts b from a
template <>
int Function<int>(int a, int b)
{
return a-b;
}
int main()
{
double d = Function(5.0, 3.0); // return 8.0
int i = Function(5, 3); // return 2
}
Now of course, you can use the above to make a type test as well, although this may result in unoptimal code, or even code that doesn't compile if the branch-not-taken doesn't 'work' for the type.
Code:
// generic template
template <class T>
bool isint()
{
return false; // generic types aren't int
}
// specialize for int
template <>
bool isint<int>()
{
return true; // only an int is an int
}
template <class myType>
myType Function(myType a, myType b)
{
if (isint<myType>())
{
//Do Int stuff
return a-b; // This wil fail to compile if myType doesn't have a binary + operator.
}
else
{
//Do non-int stuff
return a.GetValue() + b.GetValue() // this won't compile for int, it will compile for types that have a GetValue() that is addable.
}
}
Note that the compiler will typically be able to "optimize away" the branch not taken, but even if so, it still needs to be able to compile that branch in the first place.
Tags for this Thread
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|