模板函数,用于涵盖具有不同返回类型的旧C函数

时间:2017-12-01 16:55:10

标签: c++ c++11 templates

我需要在C ++中编写一个模板函数来覆盖一些传统的C函数。

我将尝试使用以下示例代码解释这种情况。

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
}

请注意,C函数的返回类型也不同。另请注意,我无法控制C函数或定义的结构。

如何使用C ++ 11中的模板正确实现myCPPFunction函数?

我已经问了一个类似的问题并在Covering legacy C style functions using C++ template

得到了答案

但是返回类型不再是这个问题的基本类型,解决方案表明这种情况有效!

1 个答案:

答案 0 :(得分:1)

过载:

MyStruct_float myCPPFunction(float a, float b) { return myCFunction_float(a, b); }
MyStruct_double myCPPFunction(double a, double b) { return myCFunction_double(a, b); }

或者制作一个为您执行此操作的重载对象。这在C ++ 11中比在C ++ 17中更复杂,但它仍然非常可行:

template <typename T, typename... Ts>
struct overloader : overloader<T>::type, overloader<Ts...>::type
{
    using type = overloader;
    using overloader<T>::type::operator();
    using overloader<Ts...>::type::operator();

    template <typename U, typename... Us>
    explicit overloader(U&& u, Us&&... us)
        : overloader<T>::type(std::forward<U>(u))
        , overloader<Ts...>::type(std::forward<Us>(us)...)
    { }
};

template <typename T>
struct overloader<T> {
    using type = T;
};

template <class R, class... Args>
class overloader<R(*)(Args...)>
{
public:
    using type = overloader;

    explicit overloader(R (*p)(Args...))
        : ptr_(p)
    { }

    R operator()(Args... args) const
    {
        return ptr_(std::forward<Args>(args)...);
    }

private:
    R (*ptr_)(Args...);
};


template <typename... Ts>
overloader<typename std::decay<Ts>::type...>
overload(Ts&&... ts) {
    return overloader<typename std::decay<Ts>::type...>(std::forward<Ts>(ts)...);
}

有了这个:

auto myCPPFunction = overload(MyCFunction_float, MyCFunction_double);
相关问题