简体   繁体   English

如何在C ++中模拟templatised std :: function

[英]How emulate a templatised std::function in C++

Following is a basic instance of what I am doing in my C++ program. 以下是我在C++程序中所做的基本实例。 I have a list of listeners which are all std::function s. 我有一个监听器列表,它们都是std::function s。 I have a concept DataType which means what kind of data the listener is interested in. The idea here is the same as publish-subscribe pattern. 我有一个概念DataType ,它意味着听众感兴趣的是什么类型的数据。这里的想法与发布 - 订阅模式相同。 A method interested in certain kind of data should be able to add itself to the list of listeners using AddListener . 对某种数据感兴趣的方法应该能够使用AddListener将自己添加到侦听器列表中。 Some methods are added & they receive a callback whenever required. 添加了一些方法,并在需要时接收回调。

The program works fine !! 该程序工作正常!!

#include <iostream>
#include <functional>
#include <vector>
#include <string>

enum class DataType {
  Type_1,
  Type_2
  // and so on
};

typedef std::function<void(std::pair<DataType, std::string>)>   MyListenerType;

//template <typename T>
//typedef std::function<void(T>)>   MyListenerType;
// How can I emulate the above so that a method passing any kind of primitive data-type namely "int, bool, float or double" can be added into
// my vector of listners.


std::vector<MyListenerType>      my_data_listeners_1;
std::vector<MyListenerType>      my_data_listeners_2;

void ListenerMethod_Instance_1(std::pair<DataType, std::string> information) {

  DataType data_type = information.first;
  std::string message = information.second;
  std::cout << "ListenerMethod_Instance_1 called with message " << message << "\n";
}

void ListenerMethod_Instance_2(std::pair<DataType, std::string> information) {

  DataType data_type = information.first;
  std::string message = information.second;
  std::cout << "ListenerMethod_Instance_2 called with message " << message << "\n";
}

void AddListener (MyListenerType listener, DataType type_of_interest) {

  if (DataType::Type_1 == type_of_interest) {
    my_data_listeners_1.push_back(listener);
    std::cout << "Added a method instance for DataType::Type_1" << "\n";
  }
  else if (DataType::Type_2 == type_of_interest) {
    my_data_listeners_2.push_back(listener);
    std::cout << "Added a method instance for DataType::Type_2" << "\n";
  }
  else {
    std::cout << "Listener type not supported" << "\n";
  }
}

void CallAllListnersWhohaveSuscribed() {

  if (!my_data_listeners_1.empty()) {
    std::string send_message_1 = "some message 123";
    std::pair <DataType, std::string> info_to_send_1 = std::make_pair (DataType::Type_1, send_message_1);
    for(auto const  &listener : my_data_listeners_1) {
      listener(info_to_send_1);
    }
  }

  if (!my_data_listeners_2.empty()) {
    std::string send_message_2 = "some message 456";
    std::pair <DataType, std::string> info_to_send_2 = std::make_pair (DataType::Type_2, send_message_2);
    for(auto const  &listener : my_data_listeners_2) {
      listener(info_to_send_2);
    }
  }
}

int main() {

  // Add ListenerMethod_Instance_1 for instance
  DataType data_type_1 = DataType::Type_1;
  auto listener_instance_1 = std::bind(ListenerMethod_Instance_1, std::placeholders::_1);
  AddListener(listener_instance_1, data_type_1);

  // Add ListenerMethod_Instance_2 for instance
  DataType data_type_2 = DataType::Type_2;
  auto listener_instance_2 = std::bind(ListenerMethod_Instance_2, std::placeholders::_1);
  AddListener(listener_instance_2, data_type_2);

  CallAllListnersWhohaveSuscribed();
  return 0;
}

Following is the output of the program: 以下是该计划的输出:

./stdFunctionTest
Added a method instance for DataType::Type_1
Added a method instance for DataType::Type_2
ListenerMethod_Instance_1 called with message some message 123
ListenerMethod_Instance_2 called with message some message 456

But here is how I want to modify & struggling with. 但这就是我想要修改和挣扎的方式。 The caveat is that every ListenerMethod_Instance_1 & ListenerMethod_Instance_2 have to parse the pair to get their info which I don't want to. 需要注意的是,每个ListenerMethod_Instance_1ListenerMethod_Instance_2都必须解析该对以获取我不想要的信息。 I want to enable a method of any C++ primitive data type be it "int, bool, float or double" to be able to be added into the listeners vector & receive the callback . 我想启用任何C ++原始数据类型的方法,无论是“int,bool,float还是double”,都可以添加到侦听器向量中并接收回调 For example following method should be "add-able" into AddListener . 例如,以下方法应该“添加”到AddListener

void ListenerMethod_Instance_3(int integer_data) {

  std::cout << "ListenerMethod_Instance_3 called with integer_data " << integer_data << "\n";
}

Looking at this link here looks somewhat possible someway. 看这个链接在某种程度上看起来有点可能。 But I'm struggling to adapt it to my use-case here. 但是我在努力使它适应我的用例。 Please suggest. 请建议。

So, basically how can I achieve templates functionality with std::function s ? 那么,基本上我如何用std::function s实现模板功能呢?

struct anything_view_t {
  void* ptr=0;
  template<class T, std::enable_if_t<!std::is_same<anything_view_t, std::decay_t<T>>{}, int> =0>
  anything_view_t(T&&t):ptr(std::addressof(t)){}
  anything_view_t()=default;
  anything_view_t(anything_view_t const&)=default;
  anything_view_t& operator=(anything_view_t const&)=default;
  template<class T>
  operator T() const { return *static_cast<T*>(ptr); }
};

this is a very unsafe type erasing view of anything. 这是一种非常不安全的类型擦除视图。

struct any_callbacks {
  std::unordered_map<std::type_index, std::vector<std::function<void(anything_view_t)>>> table;
  template<class T>
  void add_callback( std::function<void(T)> f ){
    table[typeid(T)].push_back(f);
  }
  template<class T>
  void invoke_callbacks(T t) const {
    auto it = table.find(typeid(T));
    if (it==table.end()) return;
    for(auto&&f:it->second)
      f(t);
  }
};

something like the above should work. 像上面这样的东西应该工作。 The type T must match exactly. 类型T必须完全匹配。 References not supported. 参考不受支持。 Code not compiled, design is sound, probably has typos. 代码未编译,设计合理,可能有拼写错误。

This is not restructed to primitive types. 这不会被重构为原始类型。 You should pass T explicitly, don't rely on deduction as that is fragile. 你应该明确地传递T ,不要依赖扣除,因为它是脆弱的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM