c++ - 如何复制 boost 信号的槽

标签 c++ boost boost-signals

有没有办法让插槽连接到信号?即,我想将信号槽从类的一个实例复制到另一个实例

我在类里面有一个信号并遇到了以下错误。这可能是因为在 STL 容器中使用了此类。

1>c:\boost_1_52_0\boost\signals\detail\signal_base.hpp(150): error C2248: 'boost::noncopyable_::noncopyable::noncopyable' : cannot access private member declared in class 'boost::noncopyable_::noncopyable'
1>          c:\boost_1_52_0\boost\noncopyable.hpp(27) : see declaration of 'boost::noncopyable_::noncopyable::noncopyable'
1>          c:\boost_1_52_0\boost\noncopyable.hpp(22) : see declaration of 'boost::noncopyable_::noncopyable'
1>          This diagnostic occurred in the compiler generated function 'boost::signals::detail::signal_base::signal_base(const boost::signals::detail::signal_base &)'
1>  test.cpp

所以,我决定放置一个复制构造函数并将信号连接到参数信号的插槽,然后出现以下错误,

1>d:\workarea\boostsignalsEx\test.h(26): error C2663: 'boost::signal1<R,T1>::connect' : 2 overloads have no legal conversion for 'this' pointer
1>          with
1>          [
1>              R=void,
1>              T1=int
1>          ]

如果我删除复制构造函数参数的 const 限定符,我会得到另一个错误..

1>d:\workarea\boostsignalsEx\test.h(40): error C2558: class 'test' : no copy constructor available or copy constructor is declared 'explicit'

这是我正在处理的示例代码

class test{
public:
boost::signal1<void, int> sig;
test(const test& t) { t.sig.connect(sig);}; 
void attach(boost::function1<void, int> f) {sig.connect(f);}
};

我猜链接信号是行不通的,因为我不确定复制构造函数参数对象是否会活出“这个”对象

最佳答案

您只需将信号连接到新目标:

查看 Live on Coliru

#include <boost/signals2.hpp>

typedef void(Sigature)(int);
typedef boost::signals2::signal<Sigature> Signal;
typedef Signal::slot_type                 SlotType;

class test{
    public:
        Signal sig;

        test() = default;
        test(const test& other) { *this = other; };

        test& operator=(test const& other) { sig.connect(other.sig); return *this; }

        void attach(SlotType const& f)   { sig.connect(f); }
        void trigger(int i) const        { sig(i); }
};

int main()
{
    test a, b;
    a.attach([](int i) { std::cout << "subscribed to a:      " << i << "\n"; });
    a.attach([](int i) { std::cout << "also subscribed to a: " << i << "\n"; });

    std::cout << "Trigger via a:\n";
    a.trigger(42);

    b = a;

    std::cout << "\nNow via b:\n";
    b.trigger(43);
}

打印

Trigger via a:
subscribed to a:      42
also subscribed to a: 42

Now via b:
subscribed to a:      43
also subscribed to a: 43

关于c++ - 如何复制 boost 信号的槽,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20420751/

相关文章:

c++ - 将 boost::signals2::trackable 与 lambda 一起使用

c++ - 多久从 boost::signals::trackable 派生一次?

c++ - Array2 中的更改对 Array(表)有影响

c++ - 如何在 C++ 中检查打开的进程?

c++ - Trilinos - C++ : error trying to exec 'cc1plus' : execvp: No such file or directory

c++ - 共享内存大小计算c++

c++ - 为什么这个 boost::spirit::qi 规则与输入不匹配?

c++ - Boost.预处理器 : BOOST_PP_TUPLE_ELEM and BOOST_PP_SEQ_ELEM

c++ - boost::signal slot_type 模板

c++ - 提高 fgetc 性能