如何将一个可以使用不同数值类型的C函数库包装到C ++模板类中 [英] How to wrap a C function library that works with different numeric types into a C++ template class
问题描述
我想使用C库中的代码(我的具体示例: FFTW )来实现C ++类模板。 C库定义了一些数据类型和功能,它们做同样的事情,但是在不同种类的原始数字类型上,例如fftw_complex(双双)vs fftwf_complex(一对浮标); fftw_execute()vs. fftwf_execute()等等。
我想实现一个只依赖于这种原始类型的类模板,例如
FFT< float>,FFT< double>,FFT< long double>
在本示例中,库遵循所有函数和数据具有相同前缀的约定,用于指定其使用的数据类型,因此我可以做一些非常丑陋的宏,但我宁愿不去。
有没有人知道实现这一点的优雅方式?
编辑 / p>
在SergeyA的请求下的一个显式示例:我想定义一个模板类FFT< typename T>使得FFT< double>专门用于
class FFT {
private:
fftw_complex * _data;
...
public:
execute(){
fftw_execute(...);
}
};
和
FFT< float>专门用于
class FFT {
private:
fftwf_complex * _data;
...
public:
execute(){
fftwf_execute(...);
}
};
我不知道我抓住了问题。
使用部分专业化的东西可以解决?
template< class T>
class Fwd {}
template<>
class Fwd< double> {
void execute(std :: pair< double,double> pp){
fftw_execute(pp);
}
}
template<>
class Fwd< float> {
void execute(std :: pair< float,float> pp){
fftwf_execute(pp);
}
}
//等等...
I want to use code from a C library (my specific example: FFTW) to implement a C++ class template. The C library defines some data types and functions that do the same thing, but on different kinds of primitive numeric types, e.g. fftw_complex (pair of doubles) vs. fftwf_complex (pair of floats); fftw_execute() vs. fftwf_execute(), and so on.
I would like to implement a class template that only depends on this primitive type, e.g.
FFT<float>, FFT<double>, FFT<long double> etc.
In this example the library follows the convention that all functions and data have the same prefix that specifies the data type they work with, so I might be able to do something very ugly with macros, but I would prefer not to.
Does anyone know of an elegant way to achieve this?
EDIT
An explicit example at the request of SergeyA: I would like to define a template class FFT<typename T> such that FFT<double> specializes to something like
class FFT {
private:
fftw_complex* _data;
...
public:
execute() {
fftw_execute(...);
}
};
and
FFT<float> specializes to something like
class FFT {
private:
fftwf_complex* _data;
...
public:
execute() {
fftwf_execute(...);
}
};
I'm not sure I've caught exactly the problem. Something like that using partial specialization could solve?
template<class T>
class Fwd { }
template<>
class Fwd<double> {
void execute(std::pair<double, double> pp) {
fftw_execute(pp);
}
}
template<>
class Fwd<float> {
void execute(std::pair<float, float> pp) {
fftwf_execute(pp);
}
}
// and so on...
这篇关于如何将一个可以使用不同数值类型的C函数库包装到C ++模板类中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!