Mik*_*yke 3 c++ arrays this c++11
我试图初始化模板类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;
}
Run Code Online (Sandbox Code Playgroud)
如何将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>{}) {}
};
Run Code Online (Sandbox Code Playgroud)
附注:
print会员功能应标记const为不会修改您的会员.cl[NUM - 1].print_num();你可能想用std::array::back().