根据C ++模板类型调用不同的C函数 [英] Calling different C functions according to the C++ template type

查看:100
本文介绍了根据C ++模板类型调用不同的C函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题如下:我有一个C库,其中包含每个函数的不同版本,具体取决于它们使用的数据类型,例如:

my problem is the following: I have a C library which contain several versions of each function according to which data type they are working with e.g.:

void add(double *a, double *b, double *c);

void sadd(float *a, float *b, float *c);

现在,有了外部C ++模板功能,我希望能够执行以下操作:

Now, having an external C++ template function, I would like to be able to do something like:

template<class T>
void myfunc(/*params*/)
{
 // Obtain a,b,c of type T* from params

/*
 If T is double call add(a,b,c);
 else if T is float call sadd(a,b,c).
*/ 
}

我知道可以通过专门的模板功能来完成,例如:

I am aware that It can be done by specialized template functions like:

template<>
void myfunc<double>(/*params*/)
{
  // Obtain a,b,c of type double* from params
  add(a,b,c);
}

,依此类推,但这并不是一个真正的选择,因为引入模板化C ++函数的全部目的是减少代码重复,并且"//从params中获取类型T *的a,b,c"部分可以是真的很长.

and so on, but it is not really an option since the whole point of introducing the templated C++ function was to reduce code repetition and the "// Obtain a,b,c of type T* from params" part can be really long.

这个问题有简单的解决方法吗?

Does this problem have a simple solution?

谢谢

Zdenek

推荐答案

定义重载的C ++转发器:

Define overloaded C++ forwarders:

inline void forward_add(double *a, double *b, double *c) { add( a, b, c ); }
inline void forward_add(float *a, float *b, float *c) { sadd( a, b, c ); }

template<class T>
void myfunc(/*params*/)
{
   // Obtain a,b,c of type T* from params
   forward_add( a, b, c );
}

这篇关于根据C ++模板类型调用不同的C函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆