簡體   English   中英

用'this'指針初始化std :: array

[英]initialize std::array with 'this' pointer

我試圖在模板類中初始化一個數組,並將this指針傳遞給數組中的所有元素。 這是我的類可能是這樣的:

template<int NUM> class outer_class;

template<int N>
class inner_class {
  private:
   outer_class<N> *cl;
  public:
   inner_class(outer_class<N> *num) {
    cl = num;
   }
   void print_num() {
    cl->print_num();
   }

};

template<int NUM> class outer_class {
 private:
  int number = NUM;

  // --> here I basically want NUM times 'this' <-- 
  std::array<inner_class<NUM>, NUM> cl = { this, this, this, this }; 

 public:

  void print_num() {
    std::cout << number << std::endl;
  }

  void print() {
    cl[NUM - 1].print_num();
  }
};

int main() {
  outer_class<4> t;
  t.print();

  return 0;
}

我怎樣才能通過this指針中的所有元素inner_class存儲陣列中outer_class (在C ++ 11)?

首先,你不能在構造函數或任何其他成員函數之外使用this 在這里,您必須在初始化列表中初始化cl

使用委托構造函數std :: * _ sequence的東西:

template<int NUM> class outer_class {
    ...

    template <std::size_t... Integers>
    outer_class(std::index_sequence<Integers...>) 
    : cl{(static_cast<void>(Integers), this)...}
    {}

public:
    outer_class(/* whatever */) : outer_class(std::make_index_sequence<NUM>{}) {}
};

附注:

  • 您的print成員函數應標記為const因為它們不會修改您的成員。
  • cl[NUM - 1].print_num(); 你可能想使用std::array::back()

您可以使用一些輔助函數,然后使用這些函數初始化成員,例如:

template <std::size_t I, class T>
T copy(T t) { return t; }

template <class T, std::size_t... Is>
constexpr std::array<T, sizeof...(Is)> copy_n(T const& t, std::index_sequence<Is...>) {
    return {copy<Is>(t)... };
}

template <class T, std::size_t N>
constexpr std::array<T, N> copy_n(T const& t) {
    return copy_n(t, std::make_index_sequence<N>{});
}

然后在你的班上:

std::array<inner_class<NUM>, NUM> cl;

outer_class() : cl(copy_n<inner_class<NUM>, NUM>(this)) { }

注意:

  • [待驗證]你不能在默認的成員初始化程序中使用this ,所以你需要有一個自定義構造函數;
  • 你需要明確指定inner_class<NUM>作為第一個模板參數copy_n ,因為otherwize T會被推斷為outer_class<NUM>* ,雖然有來自隱式轉換outer_class<NUM>*inner_class<NUM>有沒有從std::array<outer_class<NUM*>, NUM>std::array<inner_class<NUM>, NUM> ;
  • 如果您使用的是C ++ 11而不是14或clang ,則可能會在copy_nreturn時收到警告,您可以通過添加一對額外的括號{}來消除它。

暫無
暫無

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

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