【发布时间】:2014-09-17 08:46:48
【问题描述】:
这是我现在在嵌套类中面临的一个“国际象棋++”问题, 虽然它看起来像是一个笑话,但这不是一个笑话,而是我想要解决或改变方式以在我的项目中实现相同目标的真实问题。
#include <map>
#include <memory>
#include <iostream>
#include <sigc++/signal.h>
class foo
{
public:
struct bar;
typedef sigc::signal<void, std::shared_ptr<bar>> a_signal;
struct bar
{
bar()
{
some_signal.connect(sigc::mem_fun(*this, &foo::bar::func));
}
void notify()
{
some_signal.emit(this); // how to ??
}
void func(std::shared_ptr<foo::bar> ptr)
{
std::cout << "you haxor!" << std::endl;
// use the pointer ptr->
}
a_signal some_signal;
};
std::map<int, std::shared_ptr<bar>> a_map;
};
int main()
{
std::shared_ptr<foo::bar> a_foo_bar;
foo foo_instance;
foo_instance.a_map.insert(std::pair<int, std::shared_ptr<foo::bar>>(4, a_foo_bar));
foo_instance.a_map.at(0)->notify();
return 0;
}
我在这里要做的是发出一个信号。 该信号被声明为触发以 shared_ptr 作为参数的处理程序的信号。 函数 notify() 应该将 *this 转换为 shared_ptr,我该怎么做才能让上面的代码运行?
【问题讨论】:
-
std::shared_from_this
-
Reference for said function(注意你的类必须继承自相应的类)
标签: c++ class signals shared-ptr