由于我无法正确设计课程,我达到了需要这样的地步:
struct A
{
A( function< void(string&) cb > ): callback(cb) {}
function< void(string&) > callback;
template <std::size_t T>
void func( string& str) { ... }
}
int main(){
vector<A> items = {
A( bind( &A::func<1>, items[0], _1) ),
A( bind( &A::func<2>, items[1], _1) ),
...
}
Run Code Online (Sandbox Code Playgroud)
这样安全吗?如果没有,有替代方案吗?
这当然不安全.在items[0]会前进行评估items被初始化.
在这里做的正确的事情可能只是使用lambda,就像
vector<A> items = {
A( [&items](string& s){ items[0].func(s); } ),
A( [&items](string& s){ items[1].func(s); } ),
...
}
Run Code Online (Sandbox Code Playgroud)
这只是items在初始化期间获取引用,然后items[0]仅在实际调用回调时才撤出.
或者,您可以更改回调以将其A&作为参数吗?如果您的回调类型是,std::function<void(A&, string&)>那么您可以&A::func<1>作为回调传递,它将工作.