0

我正在尝试将升压信号和插槽与 C++ 模板一起使用。这是示例代码:

#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;
}

当我编译时,我得到(编译)错误说:

  1. typedef 模板是非法的
  2. 语法错误:缺少 ';' 在标识符“Sig_t”之前

在模板中使用升压信号是否有任何限制?仅供参考 - 我没有使用 C++11。

非常感谢任何建议/帮助。

4

2 回答 2

2

模板 typedef非法的,但你可以using在 C++11 中使用:

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

在 C++03 中,

您可以封装在一个结构中:

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

然后使用Sig<T>::type.

编辑:以下内容可能会对您有所帮助:

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;
};
于 2014-08-14T15:05:23.127 回答
0

你的问题是你引用的typedef 模板是非法的。它是,你不能有一个模板 typedef,它与 boost::signals 没有太大关系。

在 C++11 中,他们引入了您可以使用的类型别名

template<class T> using Sig_t = <your type>
于 2014-08-14T15:06:18.223 回答