我正在尝试制作一个通用的、纯虚拟的 Matrix 类,它支持返回 mew Matrix 的方法。当然,如果其中一个方法用于 Matrix 的子类,它应该返回子类类型的东西,而不是 Matrix。
目前我的代码是这样的:
class Matrix
{
virtual auto transposed() const -> decltype (*this) = 0 ;
} ;
class DenseMatrix : Matrix
{
auto transposed() const -> decltype (*this)
{
DenseMatrix res ;
// Do some magic
return res ;
}
} ;
但是,由于 decltype(*this) 是 DenseMatrix& 而不是 DenseMatrix 类型,因此代码失败,因为它最终返回了对局部变量的引用。
我如何告诉 C++ 我想要返回一个值而不是一个引用?或者,是否有任何更简洁的方法来实现返回调用它们的类的类型的虚函数?
最佳答案
如果你想从一个类型中移除引用,你可以简单地使用 std::remove_reference
。
然而,另一种解决此类问题的通用方法是使用静态多态性,也就是 CRTP:
struct MatrixBase
{
// here goes all stuff which is independent of the actual matrix,
// like number of rows, columns, etc.
};
template<typename Derived>
struct Matrix : public MatrixBase
{
virtual auto transposed() const -> Derived
{
return static_cast<Derived const&>(*this).transposed();
}
// ...
};
struct DenseMatrix : public Matrix<DenseMatrix>
{
virtual auto transposed() const override -> DenseMatrix
{ /* implementation */ }
// ...
};
这种策略通常比对基类指针使用动态多态性要快一些。例如,Eigen 库也使用 CRTP。
关于c++ - 使用 auto 和 decltype 使函数返回其类的类型。我怎样才能让它返回一个值,而不是一个引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20556975/