Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extracting calling convention from a function type using template metaprogramming in c++

Tags:

c++

templates

This is a fairly long shot, as I'm not sure it's possible, but maybe somebody more experienced than me in template metaprogramming will enlighten me.

I'm writing an automated lua function binding system using templates, extracting the function type using partial specialization:

template<typename T, T FUNCTION> class Function_c;
template<typename R, R (*FUNCTION)()> class Function_c<R (*)(), FUNCTION>; //specialized version

Problem is, this doesn't tell me the function calling convention, so (in VS2012 32 bits) it won't compile for __stdcall, and it will crash with __fastcall. I can create another specialized version to deal with a particular calling convention, eg:

template<typename R, R (__stdcall *FUNCTION)()> class Function_c<R (__stdcall *)(), FUNCTION>;

But the number of permutations is starting to get out of hand: 2 (global & member functions) times max number of parameters times number of calling conventions.

So I'm wondering if there's any way to get the calling convention as a template parameter (probably not, since it's not really a type) to cut down on the amount of copypasting.

like image 742
Seol Avatar asked Dec 27 '12 18:12

Seol


1 Answers

When you are dealing with this type of parameter, what you can do is one of the following.

Add one extra parameter

Your template will then look like this:

template < typename T, T function, typename CallType > class Function_c;

You can easily hide the actually dispatch inside the CallType, thus you will only need to implement one class for each type of call.

Make a wrapper

I'm guessing that your class is already a wrapper object, but you can easily go one step further.

You can create a wrapper for each of the call types, can then change the template to:

template < typename T, typename Functor > class Function_c;

Instanciating like this: Function_c<int, WrapperStdCall<int (*)()> > x;

like image 82
Šimon Tóth Avatar answered Nov 09 '22 01:11

Šimon Tóth