封装ublas并重载operator()的const引用版本
Implementing the Const Reference
operator() for UblasEncapsulated Alright, let's tackle this const reference overload for your UblasEncapsulated class. Here's the complete implementation with the missing const version, plus breakdowns of the key details:
#include <boost/numeric/ublas/matrix_sparse.hpp> #include <iostream> namespace ublas = boost::numeric::ublas; class UblasEncapsulated { private: ublas::compressed_matrix<float> mtr_; bool MtrUpdated_ = false; // Assumed this is a member variable you declared public: // Your existing non-const reference version ublas::compressed_matrix<float>::reference operator()(int i, int j){ std::cout << "Non const reference" << std::endl; MtrUpdated_ = true; return mtr_(i, j); } // The const reference overload you need ublas::compressed_matrix<float>::const_reference operator()(int i, int j) const { std::cout << "Const reference" << std::endl; // Can't modify MtrUpdated_ here—const member functions can't alter non-mutable members return mtr_(i, j); } };
Key Details to Understand:
- Const Function Qualifier: The
constat the end of the function signature marks this as a const member function. It lets you call this operator on const instances ofUblasEncapsulated, and guarantees it won't modify any non-mutable class members. - Const Return Type: Using
const_referenceensures the returned matrix element can't be modified through this operator, which preserves const correctness. - No Member Modifications: Since this is a const function, we can't set
MtrUpdated_ = truehere (unless you declareMtrUpdated_asmutable—but that's only recommended if you have a specific, justified need for it, as it weakens const guarantees). - Matrix's Const Operator: When we call
mtr_(i,j)inside this const function, it automatically invokes the const version ofcompressed_matrix'soperator(), which returns aconst_reference—exactly what we need for this overload.
内容的提问来源于stack exchange,提问作者aaamourao
相关产品推荐
相关产品推荐

