我有一個基于模板的 Vector 類。我有一個單位轉換模板,它基于C 中的 Scott Meyers Dimensional Analysis。我不打算列出它,因為它很復雜,除非沒有這些細節問題就無法解決。當我需要將資料傳遞給外部函式時,我正在使用轉換運算子。
template<typename T>
struct XYZVector
{
operator Point3D() { return Point3D(x, y, z); }
}
如果我使用 T 作為雙精度它作業正常。但是當我這樣做時,我需要專業化。
Point3D vecOut = XYZVector<Unit::usFoot>(x,y,z);
會失敗,因為在轉換 Unit 物件時需要使用 as() 方法。
operator Point3D() { return Point3D( x.as<T>(), y.as<T>(), z.as<T>() ); }
所以我需要以某種方式說如果 T 是一個單位使用這一行,否則使用下一行。
template<typename T>
struct XYZVector
{
//if typename T is a Unit type use this
operator Point3D() { return Point3D( x.as<T>(), y.as<T>(), z.as<T>() ) }
//otherwise use this
operator Point3D() { return Point3D(x, y, z); }
}
這可能嗎?
uj5u.com熱心網友回復:
if constexpr 到救援。
operator Point3D() {
if constexpr (std::is_same_v<std::remove_cvref_t<T>,Unit>){
return Point3D(x.as<T>(),y.as<T>(),z.as<T>());
}else{
return Point3D(x,y,z);
}
}
uj5u.com熱心網友回復:
我會使用多載作為自定義點:
// overload for built-in type (no ADL)
double to_double(double d) { return d;}
template <typename T>
struct XYZVector
{
// ...
operator Point3D() const {
return Point3D(to_double(x),
to_double(y),
to_double(z));
}
};
// The ones which can be found by ADL can be placed after
namespace Unit {
double to_double(usFoot u) { return u.as<double>(); }
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/342884.html
