使用C ++模板涵盖旧的C样式函数 [英] Covering legacy C style functions using C++ template

查看:40
本文介绍了使用C ++模板涵盖旧的C样式函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在C中具有以下两个函数。

I have the following two functions in C.

float floatAdd(float a, float b)
{
    return a+b;
}

double doubleAdd(double a, double b)
{
    return a+b;
}

现在,我想结合两个函数并在C ++中编写一个tempalte函数

Now, I would like to combine both functions and write a tempalte function in C++ as follows.

template<class T>
T add(T a, T b)
{
    // if T=float, return floatAdd(a,b)
    // if T=double, return doubleAdd(a,b)

}

由于返回类型不同,我

请注意,上述功能非常简单,仅用作示例。我的目的是为示例说明的那种旧版C函数提供C ++模板包装。

Please note that the above functions are very simple, and used as merely an example. My intention is provide a C++ template wrapper for some Legacy C functions the kind explained the example.

推荐答案

您的示例并非如此显示需要使用特定功能。但是在更一般的情况下,您可以为给定的一组模板参数提供模板函数或模板类的特定实现。该功能称为模板专业化,并且专门用于解决此问题。

Your example doesn't really show the need to use the specific functions. But in a more general case, you can provide a specific implementation for a template function or template class for a given set of template arguments. The feature is known as Template specialization and is specifically designed to address this problem.

template<class T>
T add(T a, T b);

// Special implementation for floatAdd
template<>
float add<float>(float a, float b)
{
    return floatAdd(a, b);
}

// Special implementation for floatDouble
template<>
double add<double>(double a, double b)
{
    return doubleAdd(a, b);
}

对于这种简单情况,您可以简单地使用常规模板:

For such a simple case, you can simply use a regular template :

template<class T>
T add(T a, T b)
{
    return a + b;
}

如果您不关心支持一般情况,则可以使用函数重载而忘了模板:

If you don't care about supporting a general case, you can just use function overloading and forget about templates :

float add(float a, float b)
{
    return floatAdd(a, b);
}

double add(double a, double b)
{
    return doubleAdd(a, b);
}

这篇关于使用C ++模板涵盖旧的C样式函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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