开发者

Insert a class method in map value and use template

Suppose I have the following:

class X
{
  private:开发者_如何学Go
    typedef int (X::*xMethod) (float*);

    typedef std::map<std::string, xMethod> callback_t;

    callback_t m_callback;

  public:

    getPower(float *value);
    getTemperature(float *value);
}

In the example above, in map key we are passing an string, and in map value a pointer to a method of class X. To insert in this map, for example, I'm using:

m_callback.insert(std::pair<std::string, xMethod>("voltage", &X::getPower));

Using this, I can only insert methods if they are of type METHOD_NAME(float *value)

However, I want to insert in the map methods of type __METHOD_NAME__(int *value) for example (see 'int' instead of 'float' here).

I suppose that to do this, I need a template. But how? Is there a way to solve this?


There is no template typedef in C++98, but you can wrap the genericity into a helper struct. The example code shows both your own version and my generic version side by side.

#include <map>
#include <string>

class Foo
{
  typedef int (Foo::*xMethod)(float*);
  typedef std::map<std::string, xMethod> cb_map;

  template <typename T> struct CBHelper
  {
    typedef int (Foo::*fptype)(T*);
    typedef std::map<std::string, fptype> type;
  };

  cb_map m_cb_float;
  CBHelper<int>::type m_cb_int;

public:
  int getF(float *);
  int getI(int *);
  Foo()
  {
    m_cb_float.insert(cb_map::value_type("Hello", &Foo::getF));
    m_cb_int.insert(std::make_pair("Hello", &Foo::getI));
  }
};
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜