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?
Code Example:
prints 9, that means that used int function
auto
requires c++0x, you may use real typename instead, but it's ugly and you'll need check changing signature too. Besides, this code, may disallow your compiler to inline this functionAs for me, it's often better use full name with
<>
In your case you need not use
<>
becausemyFunc
is enough(DataType
may be got from argument type)I would make a just tiny improvement over Xeo's answer.
Instead of using:
I would use
Use
decltype
:Try this:
This will trigger a compiler error if the signature of
myFunc
ever changes. Making itconst
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 withconst
):Some may disagree, some may jerk their knees against this, but consider this option:
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 wantauto
but don't want to use C++0x features yet, this is a more portable way to achieve the same effect.