Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best alternative to a typedef for a function template?

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?

like image 336
Paul Molodowitch Avatar asked Dec 16 '11 23:12

Paul Molodowitch


People also ask

Which is best suited syntax for template function?

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.

Is using better than Typedef?

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.

Does function template work with string?

The template function works for int and char, but not float and string.

Can you have a virtual template function?

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.


2 Answers

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>;
like image 162
Xeo Avatar answered Oct 27 '22 08:10

Xeo


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.

like image 41
Chris Lutz Avatar answered Oct 27 '22 08:10

Chris Lutz