Search code examples
c++templatesboost-signals2

C++ template class with boost signals2


I'm trying to use the boost signals and slots with C++ templates. Here is the example code:

#include <iostream>
#include <sstream>
#include <string>

#include <boost/signals2/signal.hpp>

template<class T>
class JBase
{
public:
    JBase(T &d) : data(d)
    {}
    virtual ~JBase() {}
    virtual bool DoSomething(std::string &outStr) = 0;

protected:
T data;
};

class LToUse : public JBase<int>
{
public:
   LToUse(int d) : JBase<int>(d) {}
   virtual ~LToUse() {}
   bool DoSomething(std::string &outStr)
   {
      std::ostringstream s;
      s << data;
      outStr = s.str();
      return true;
   }
};

template<class T>
typedef boost::signals2::signal<void(const JBase<T> &jsonObj)>::slot_type Sig_t;

class CBHndlr
{
   CBHndlr()
   {
      // I get errors even on this line...??
      //Sig_t t = boost::bind(&CBHndlr::TestCb, this, _1);
      //m_Signal.connect(t)
   }

   template<class T>
   void TestCb(JBase<T> *obj)
   {

   }

private:
   template<class T>
   boost::signals2::signal<void(JBase<T>)> m_Signal;
};

template<class T>
void TestJL(JBase<T> *obj)
{
   std::string s;
   obj->DoSomething(s);
   std::cout << "Did Something: " << s;
}

When I compile, I get (compilation) errors saying:

  1. typedef template is illegal
  2. syntax error : missing ';' before identifier 'Sig_t'

Are there any restrictions on using boost signals with templates? FYI - I'm not using C++11.

Any suggestions/help is much appreciated.


Solution

  • template typedef is illegal, but you may use using in C++11:

    template<class T>
    using Sig_t = typename boost::signals2::signal<void(const JBase<T> &jsonObj)>::slot_type;
    

    In C++03,

    you may encapsulate inside a struct:

    template <typename T>
    struct Sig
    {
        typedef typename boost::signals2::signal<void(const JBase<T> &jsonObj)>::slot_type type;
    };
    

    And then use Sig<T>::type.

    EDIT: The following may help you:

    template <typename T>
    class CBHndlr
    {
       CBHndlr()
       {
          typename Sig<T>::type t = boost::bind(&CBHndlr::TestCb, this, _1);
          m_Signal.connect(t)
       }
    
       void TestCb(JBase<T> *obj) {}
    private:
       boost::signals2::signal<void(JBase<T>)> m_Signal;
    };