You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

封装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 const at the end of the function signature marks this as a const member function. It lets you call this operator on const instances of UblasEncapsulated, and guarantees it won't modify any non-mutable class members.
  • Const Return Type: Using const_reference ensures 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_ = true here (unless you declare MtrUpdated_ as mutable—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 of compressed_matrix's operator(), which returns a const_reference—exactly what we need for this overload.

内容的提问来源于stack exchange,提问作者aaamourao

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 11:25:44