vendredi 1 décembre 2017

Template function to cover legacy C functions with different return types

I need to write a template function in C++ to cover some legacy C functions.

I will try to explain the situation using the following sample codes.

struct MyStruct_float
{
    float x;
    float y;

};


struct MyStruct_double
{
    double x;
    double y;

};



MyStruct_float myCFunction_float(float a, float b)
{

    MyStruct_float t;
    t.x = a;
    t.y = b;
    return t;
}



MyStruct_double myCFunction_double(double a, double b)
{

    MyStruct_double t;
    t.x = a;
    t.y = b;
    return t;
}





template<class T>
T1 myCPPFunction(T a, T b)
{
    // if T=float, return myCFunction_float(a,b). In this case, T1=MyStruct_float
    // if T=double, return myCFunction_double(a,b). In this case, T1=MyStruct_double

}

Please note that the return type of the C functions are also different. Also note that I don't have any control over the C functions or the structures defined.

How to implement the function myCPPFunction correctly using templates in C++11? I have already asked a similar question and got answer at Covering legacy C style functions using C++ template But the return type is no longer a fundamental type in this question and the solution suggested there is working in this situation!

Aucun commentaire:

Enregistrer un commentaire