簡體   English   中英

使用reference_wrapper而不是C ++ 11中的標准指針訪問類成員

[英]Accessing class members using reference_wrapper instead of standard pointers in C++11

我試圖建立一個unordered_mapvector變量,這是我班的成員。 我可以使用標准指針*來做到這一點,但這需要使用(*x)來訪問向量。 我想知道std::reference_wrapper是否會更干凈,但無法正常工作。

#include <unordered_map>
#include <iostream>
#include <vector>
#include <functional>

class model_class {

private:

  static constexpr auto MaxHerds = 1 ;
  static constexpr int MaxInitValues = 5 ;
  static constexpr int MaxAnimals = 2 ;

  std::vector< double > MamCellsF ;
  std::vector< std::vector< double > > InitCond ;

public:

  std::unordered_map< std::string , std::reference_wrapper< std::vector< double > > > vector;
  std::unordered_map< std::string , std::vector< std::vector< double > >* > array;

  model_class ( ) :
    // initialise vectors
    MamCellsF( MaxHerds , 0.07 ) ,
    InitCond( MaxAnimals , std::vector< double > ( MaxInitValues , 0.7 ) )
  {
     // point to variables from model
     vector.insert({"MamCellsF", std::ref(MamCellsF)});
     array["InitCond"] = &InitCond;

     // assign to vectors
     MamCellsF = { 0.001 , 0.002 }  ; // warning: automatic resizing
     InitCond = { { 1.0 , 550 , 3.5 , 1 , 4 } ,
     { 2.0 , 625 , 3.5 , 5 , 4 } } ;
  }

  void print_values(){

    // access the vectors
    double a = vector["MamCellsF"].get()[1]; // error: "no matching function call to `std::reference_wrapper<std::vector<double>>::reference_wrapper()"
    double b = (*array["InitCond"])[0][1];
    std::cout << a << std::endl;
    std::cout << b << std::endl;

  }

};

void test()
{

  model_class model;
  model.print_values();

}

vector["MamCellsF"]返回對映射中值的引用。 因此,如果沒有,則必須首先構造它。 它使用默認構造函數,但std::reference_wrapper無法默認構造,因此會出現錯誤。

我認為STL容器使用T是安全的,默認情況下不可構造,但其操作可能受到限制。 所以我不建議這樣做。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM