2014-03-24 42 views
0

我试图创建一个简单的滚动平均值实施通用数值类型,但都创下了绊脚石:有没有什么办法在.net(C++ - CLI)中对泛型进行分区?

generic<typename T> 
public ref class RollingMean 
{ 
protected: 
    CircularBuffer<T> m_dataBuffer; 
    T m_currentSum; 

public: 
    RollingMean(const int NumOfItems); 

    T AddItem(const T NewItem); 

    T CurrentMean() 
    { 
     return m_currentSum/static_cast<float>(m_dataBuffer.Length); // <--- gives me compiler error C2676 
    } 
}; 

这给了我一个编译器错误:

1>c:\projects\util\RollingMean.h(21): error C2676: binary '/' : 'T' does not define this operator or a conversion to a type acceptable to the predefined operator 
1>RollingMean.cpp(6): error C2955: 'MathHelpers::RollingMean' : use of class generic requires generic argument list 
1>   c:\projects\util\RollingMean.h(9) : see declaration of 'MathHelpers::RollingMean' 

有什么办法将泛型类限制为那些对数字操作满意的类?

+0

这是泛化泛型vs模板的着名局限之一。已经在很多*问题中涵盖得很好。没有通用的二元运算符,不能通过对象来分割对象:)并且不能将类型参数限制为支持它的值类型,运算符重载在编译时解析。使用方法重载或模板。 –

+0

我有一种感觉,可能是这种情况,但只是找不到任何明确表示你无法做到的事情。 –

+0

真的没有INumericType泛型。 –

回答

0

有没有好办法用泛型做到这一点。我建议您遵循Linq.Enumerable类设置的模式,该类为每种数字类型提供显式重载。举例来说,以Enumerable.Average为例:它提供了int,long,float,double和Decimal的重载,没有泛型重载。

相关问题