簡體   English   中英

如何為sigc ++編寫包裝類?

[英]how to write a wrapper class for sigc++?

希望有一個中心位置來注冊新信號,連接到信號等等。 現在我想使用sigc ++。 但是,我不知道如何為基於此模板的庫編寫包裝類。 類似於以下內容:

class EventManager {
public:
    ... singleton stuff ...
    template<typename ReturnType, typename Params>
    bool registerNewSignal( std::string &id )
    {
        sigc::signal<ReturnType, Params> *sig = new sigc::signal<ReturnType, Params>();

        // put the new sig into a map
        mSignals[ id ] = sig;
    }

    // this one should probably be a template as well. not very
    // convenient.
    template<typename ReturnType, typename Params>
    void emit( id, <paramlist> )
    {
        sigc::signal<ReturnType, Params> *sig = mSignals[ id ];
        sig->emit( <paramlist> );
    }

private:
    std::map<const std::string, ???> mSignals;
};

我應該更換什么? 可以使地圖通用,但仍然能夠檢索給定id的相應信號,並使用給定的參數列表發出信號-我也不知道如何處理。

您將需要一個具有generate()函數的基類:

template<class Ret>
class SigBase {
public:
  virtual Ret emit()=0;
};

然后它的一些實現:

template<class Ret, class Param1>
class SigDerived : public SigBase<Ret>
{ 
public:
  SigDerived(sigc::signal<Ret, Param1> *m, Param1 p) : m(m), p(p){ }
  Ret emit() { return m->emit(p); }
private:
  sigc::signal<Ret, Param1> *m;
  Param1 p;
};

然后,映射只是指向基類的指針:

std::map<std::string, SigBase<Ret> *> mymap;

編輯:如果SigBase不具有Ret值,而僅支持void返回,則可能會更好。

這是我到目前為止所擁有的。 它的工作原理...但感覺就像是可憎的。 我該如何進一步改善? 例如,如何擺脫reinterpret_cast?

@dimitri:感謝您提供的互斥鎖技巧,我將其添加。

class Observer {
public:

    static Observer* instance()
    {
        if ( !mInstance )
            mInstance = new Observer();
        return mInstance;
    }

    virtual ~Observer() {}

    template<typename ReturnType, typename Params>
    sigc::signal<ReturnType, Params>* get( const std::string &id )
    {
        SignalMap::const_iterator it = mSignals.find( id );
        if ( it == mSignals.end() )
            return 0;

        return reinterpret_cast<sigc::signal<ReturnType, Params>*>( (*it).second );
    }

    template<typename ReturnType, typename Params>
    bool registerSignal( const std::string &id )
    {
        SignalMap::const_iterator it = mSignals.find( id );
        if ( it != mSignals.end() ) {
            // signal with the given id's already registered
            return false;
        }

        // create a new signal instance here
        sigc::signal<ReturnType, Params> *sig = new sigc::signal<ReturnType, Params>();
        mSignals[ id ] = reinterpret_cast<sigc::signal<void>*>(sig);

        return true;
    }

private:
    Observer()
    {
    }

    SignalMap           mSignals;
    static Observer*    mInstance;
};

Observer* Observer::mInstance = 0;

暫無
暫無

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

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