gpt4 book ai didi

c++ - 如何根据类型是整型还是浮点型来更改模板方法?

转载 作者:太空狗 更新时间:2023-10-29 21:26:55 26 4
gpt4 key购买 nike

我正在研究一个 Matrix 类,它同时采用整数(short、int、long)和浮点类型(float、double)。我希望某些方法仅限于浮点类型(例如反转方法),而某些方法对浮点类型和整型具有不同的实现(例如 == 运算符)。我有一种直觉,正确的方法是使用 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,这是正确的吗?

如果是这样,我该怎么做?我知道模板特化是一种可行的方法,但我想避免重复过多的代码。

最佳答案

最简单的方法是在 Matrix 中使用重载函数:

template <typename T>
class Matrix
{
template <bool isInteger> class Discrim;
// ...
bool isEqual( Matrix const& other, Discrim<true> ) const
{
// Integer implementation...
}

bool isEqual( Matrix const& other, Discrim<false> ) const
{
// Floating point implementation...
}

public:
bool isEqual( Matrix const& other ) const
{
return isEqual( other, Discrim<std::numeric_limits<T>::is_integer>() );
}
};

您的 operator==operator!= 将调用 Matrix::isEqual,当然。

话虽如此:从您的评论来看,您想要一个“几乎相等”的如果 T 是浮点类型,则函数。不要这样做。它只会使人们感到困惑,并在以后造成无穷无尽的问题(因为 ==将不再是传递操作)。

关于c++ - 如何根据类型是整型还是浮点型来更改模板方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10283610/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com