模板函数,用于覆盖具有不同返回类型的旧C函数 我需要在C++中编写一个模板函数来覆盖一些遗留C函数。
我将尝试使用以下示例代码解释这种情况模板函数,用于覆盖具有不同返回类型的旧C函数 我需要在C++中编写一个模板函数来覆盖一些遗留C函数。,c++,c++11,templates,C++,C++11,Templates,我将尝试使用以下示例代码解释这种情况 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; }
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
}
struct MyStruct\u float
{
浮动x;
浮动y;
};
结构MyStruct\u double
{
双x;
双y;
};
MyStruct\u float myCFunction\u float(浮点a、浮点b)
{
我的结构;
t、 x=a;
t、 y=b;
返回t;
}
MyStruct\u double myCFunction\u double(双a,双b)
{
我的结构是双重的;
t、 x=a;
t、 y=b;
返回t;
}
模板
T1 mycpp函数(T a,T b)
{
//如果T=float,则返回myCFunction\u float(a,b)。在本例中,T1=MyStruct\u float
//如果T=double,则返回myCFunction\u double(a,b)。在本例中,T1=MyStruct\u double
}
请注意,C函数的返回类型也不同。还要注意,我对C函数或定义的结构没有任何控制权
如何在C++11中使用模板正确实现函数myCPPFunction
我已经问了一个类似的问题,并在
但是返回类型不再是这个问题中的基本类型,解决方案建议在这种情况下使用 只是过载:
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)...);
}
在这种情况下,函数重载应该更简单。@cpplearner:函数重载不起作用,因为我们需要在内部调用返回不同结构的不同C函数。
auto myCPPFunction = overload(MyCFunction_float, MyCFunction_double);