[英]Template function to cover legacy C functions with different return types
我需要用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?
我已经问过类似的问题,并且在使用C ++模板覆盖旧的C样式函数时得到了答案。
但是返回类型不再是此问题中的基本类型,建议的解决方案在这种情况下有效!
只是重载:
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.