Soo
Soo

Reputation: 1017

Covering legacy C style functions using C++ template

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;
}

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)

}

Since the return types are different, I am unable to find a solution!

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.

Upvotes: 2

Views: 236

Answers (1)

Fran&#231;ois Andrieux
Fran&#231;ois Andrieux

Reputation: 29022

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);
}

Upvotes: 7

Related Questions