考慮下面的指數平滑模板類。該類用於按指數順序平滑/過濾順序數據(請參閱更新方法)。 Elemtype可能是一個矢量,Floattype通常是一個標量。例如。C++檢查模板參數的嵌套typedef以獲得其標量基類型
ExponentialSmoother<Eigen::Vector2f, float> x(0.1, Vector2f(0.5, 0.5));
在這個例子中,第二個模板參數可避免Floattype因爲本徵的Matrix類包含嵌套的typedef獲得標量基本類型:
Vector2f::Scalar
這也是合理的實例都Elemtype和Floatype作爲浮動來平滑一維數據。在這種情況下,第二個模板參數也可以跳過。
template <class Elemtype, class Floattype>
class ExponentialSmoother
{
public:
// ctor
ExponentialSmoother(Floattype alpha, Elemtype& initial_estimate);
// getters
inline const Elemtype& getValue() const {return estimate_;}
inline const Floattype getAlpha() const {return alpha_;}
const Elemtype& update(const Elemtype& curr)
{
estimate_ = (alpha_ * curr) + (((Floattype)1-alpha) * estimate_);
return estimate_;
}
private:
Elemtype estimate_;
Floattype alpha_; // smoothing factor within [0,1]
}
現在我的問題是什麼是隻有一個模板參數(元素類型)實施ExponentialSmoother「最優雅」的解決方案? 它應該使用特徵向量和矩陣,但也適用於浮點類型。
換句話說,是否有可能檢查Elemtype :: Scalar是否存在,如果不存在(即Elemtype是float還是double),則將Floattype定義爲Elemtype?
一個類似的問題已被要求here。但是我想知道什麼是最通用的解決方案,例如STL向量也應該被支持。所有類型都需要相同的嵌套typedef(或者一些具有一致命名的特徵類)?
*請問各類需要相同的嵌套類型定義(或某些特質與一致的命名類)* - ?是的。 –