我正在开发一个矩阵类,可以接受整数类型(short、int、long)和浮点数类型(float、double)。
我希望某些方法只适用于浮点数类型(例如倒数方法),而某些方法对浮点数类型和整数类型有不同的实现(例如等于运算符)。
我有一种感觉,正确的方法是使用boost的“enable_if”和“is_integral”/“is_floating_point”,但我似乎无法让它起作用。
我的实现类似于以下C++半伪代码:
这会导致很多编译错误,我认为以下是最相关的错误信息:
并且。
这表示我不能使用boost的enable_if来为不同的类型提供不同的实现,这是正确的吗?
如果是这样,我该怎么办? 我知道模板特化是一种方法,但我想避免重复太多的代码。
我希望某些方法只适用于浮点数类型(例如倒数方法),而某些方法对浮点数类型和整数类型有不同的实现(例如等于运算符)。
我有一种感觉,正确的方法是使用boost的“enable_if”和“is_integral”/“is_floating_point”,但我似乎无法让它起作用。
我的实现类似于以下C++半伪代码:
template <typename T>
class Matrix
{
...
bool operator==(Matrix<typename enable_if<is_integral<T> T >::type >) const;
bool operator==(Matrix<typename enable_if<is_floating_point<T>::type T> >) const;
typename enable_if<is_floating_point<T> T> computeInverse() const;
...
};
// implementation
bool Matrix<T>::operator==(Matrix<typename enable_if<is_integral<T> T >::type >) const {
//implementation without precision
}
bool Matrix<T>::operator==(Matrix<typename enable_if<is_integral<T> T >::type >) const {
//implementation using precision
}
Matrix<typename enable_if<is_floating_point<T> T>::type > Matrix<T>::computeInverse() const {
//implementation requiring floating points
}
这会导致很多编译错误,我认为以下是最相关的错误信息:
error: no type named ‘type’ in ‘struct boost::enable_if<boost::is_integral<float>, float>’
并且。
error: no type named ‘type’ in ‘struct boost::enable_if<boost::is_floating_point<int>, int>’
这表示我不能使用boost的enable_if来为不同的类型提供不同的实现,这是正确的吗?
如果是这样,我该怎么办? 我知道模板特化是一种方法,但我想避免重复太多的代码。