c++ - 覆盖具有不同返回类型的遗留 C 函数的模板函数

标签 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 得到了答案

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

最佳答案

只是重载:

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

关于c++ - 覆盖具有不同返回类型的遗留 C 函数的模板函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47597950/

相关文章:

c++ - 使用 lambda 默认构造的 std::priority_queue

c++ - g++ 和 clang++ 不同的行为与静态成员的递归初始化

c++ - 推导出指向成员模板参数的指针

wpf - 无法通过类型(!)(wpf)找到模板化控件的父级

python - SWIG 语法错误

c++ - 从文件读入 2 个数组

android - SimpleJSON C++ 类无法在 Android (NDK) 上解析字符串,但同一类在所有其他平台上都有效

c++ - visual studio 中智能指针对象的自定义 View ?

c++ - 使用 enable_if 和 is_integral 来制作分布特征

c++ - 将 std::chrono::system_clock::time_point::min() 转换为字符串时出现无效空指针错误