What I'd like to do is something like this:
template <class DataType>
DataType myFunc(DataType in)
{
...
}
typedef myFunc<int> myFunc_i;
myFunc_i(37);
...however, typedefs cannot be used for functions like this in C++. What I was wondering is... what are people's preferred alternatives in this case? The only ones I can think of are:
1) Just deal with it, and always use myFunc syntax 2) Manually create a wrapper function, ie
inline int myFunc_i(int in)
{
return myFunc<int>(in);
}
This would work, but would have the downside of requiring extra maintenance, and the possibility that it would get out of sync (ie, if you change the function signature for myFunc).
Thoughts?
3. Which one is suitable syntax for function template? Explanation: Both class and typename keywords can be used alternatively for specifying a generic type in a template.
In C++, 'using' and 'typedef' performs the same task of declaring the type alias. There is no major difference between the two. 'Using' in C++ is considered to define the type synonyms.
The template function works for int and char, but not float and string.
You cannot have a virtual template function because as far as the compiler is concerned they are two completedly different functions; as their implicit this parameter is of different type. Another reasons why virtual templates can't work are equally valid.
Try this:
typedef int (*myFunc_i_type)(int);
myFunc_i_type const myFunc_i = &myFunc<int>;
This will trigger a compiler error if the signature of myFunc
ever changes. Making it const
also prohibits reassigning. Function pointers are also callable like any normal function: myFunc_i(5)
.
If you don't want a compiler error but rather have it update itself, use auto
(again with const
):
auto const myFunc_i = &myFunc<int>;
Some may disagree, some may jerk their knees against this, but consider this option:
#define myFunc_i myFunc<int>
As far as macros go, this one is quite safe; the only danger is that someone could redefine or undefine it later.
Aside from that, it has all the advantages of auto const myFunc = myFunc<int>;
. If you want auto
but don't want to use C++0x features yet, this is a more portable way to achieve the same effect.
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