c++ - 使用 auto 和 decltype 使函数返回其类的类型。我怎样才能让它返回一个值,而不是一个引用?

标签 c++ c++11 polymorphism auto decltype

我正在尝试制作一个通用的、纯虚拟的 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/

相关文章:

c++ - const 和非常量类型的部分 std::hash 特化

c++ - 是否有任何理由将 Lambda 包装在命名函数中?

c++ - 如何在堆栈上创建多态对象?

c++ - "Private"cpp 文件中命名空间范围内的变量

c++ - 使用 binomial_heap 和 indirect_cmp

c++11 - MS ACCESS 中的 GRANT 支持

ruby-on-rails - rails 4 : polymorphic set base class type instead of inherited

recursion - OCaml 递归调用不能有不同类型的参数?

c++ - 在 QTextEdit 中连接复制消息和主消息

c++ - 从序列中插入和删除 C++