我试图弄清楚如何创建一个 C++11 模板函数,它将在两个约定之间转换函数调用:第一个是使用 Variant(注意:变体是一种多态类型,它是子类 IntVariable 的基础, DoubleVariant 等),第二个是 C 函数调用。
我们在编译时知道每一条信息:参数计数是参数的数量,参数/返回类型取决于“cfunc”变量类型。
// We will assume that the two following functions are defined with their correct
// specializations.
template < typename T >
Variant * convertToVariant( T t );
template < typename T >
T convertFromVariant( Variant * variant );
// The following function is incomplete, the question is how to convert the
// variant parameters into a C function call ?
template < typename Return, typename... Arguments >
Variant * wrapCFunction< Return cfunc( Args... ) >(int argc, Variant ** argv) {
// Here comes the magic call of cfunc, something like :
if ( argc != mpl::count< Args... >::value )
throw std::runtime_error( "bad argument count" );
return cfunc( convertFromVariant< Args... >( argv[ X ] )... );
}
// Example use case :
int foo( int a, int b );
int main(void) {
int argc = 2;
Variant * argv[2] = { new IntVariant( 5 ), new IntVariant( 6 ) };
Variant * res = wrapCFunction< foo >( argc, argv );
IntVariant * intRes = dynamic_cast< IntVariant >( res );
return intRes ? intRes->value : -1;
}