[英]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.