如何映射通用模板化编译时函数

How to map generic templated compile-time functions

我想要某种 structure/type/map 可以包含 std::function 特化(以包含我的回调),它在编译时具有已知类型,而无需执行任何类型的操作虚拟继承或使我的所有类型都继承自基类型。

例如我想 GenericFunction 在这里保存 std::function 而不擦除已知类型,这样我可以稍后在 callback()

期间获得该类型
#include <unordered_map>
#include <string>
#include <functional>
#include <iostream>

// Example struct that I want
template<class CallbackDatatype>
struct GenericFunction{
    GenericFunction(const std::function<void(const CallbackDatatype&)> callback) 
     : m_callback(callback)

    std::function<void(const CallbackDatatype&)> m_callback;
    static T datatypePlaceholder;
}

class Test
{
public:
Test() = default;

template <class CallbackDatatype>
void attachCallback(const std::string& key, const std::function<void(const CallbackDatatype&)>& callbackFn)
{
    // How do I implement GenericFunction/a map that can hold GenericFunction??
    m_callbackMap[key] = GenericFunction<CallbackDatatype>(callbackFn)
}

// Called during runtime
void callback(const std::string& key, void* payload)
{
    const auto mapIter = m_callbackMap.find(key);
    if (mapIter != m_callbackMap.end()) {
        // I need to get the datatype of the argument specified in the std::function stored in m_callbackMap to use for deserialising my payload
        decltype(mapIter->second.datatypePlaceholder) data = m_deserialiser.deserialise<decltype(mapIter->second.datatypePlaceholder)>(payload);
        mapIter->second.m_callback(data);
    }
}

private:
Deserialiser m_deserialiser;
std::unordered_map<std::string, GenericFunction> m_callbackMap;
};

struct SomeStruct{
    int a;
    int b;
    float c;
};

int main(){

// Example int function (though I want to use more complicated structs)
const fn1 = [](const int& data) -> void {
    std::cout << data << std::endl;
}

const fn2 = [](const SomeStruct& data) -> void {
    std::cout << data.c << std::endl;
}

Test test;
test.attachCallback("Route1", fn1);
test.attachCallback("Route2", fn2);


return 0;
}

有什么办法吗?

谢谢!

您可以存储 std::function<void(void*)>,例如:

class Test
{
public:
    Test() = default;

    template <class CallbackDatatype>
    void attachCallback(
        const std::string& key,
        const std::function<void(const CallbackDatatype&)>& callbackFn)
    {
        m_callbackMap[key] = [=](void* payload){
            callbackFn(m_deserialiser.deserialise<CallbackDatatype>(payload));
        };
    }

    // Called during runtime
    void callback(const std::string& key, void* payload)
    {
        const auto mapIter = m_callbackMap.find(key);
        if (mapIter != m_callbackMap.end()) {
            mapIter->second(payload);
        }
    }

private:
    Deserialiser m_deserialiser;
    std::unordered_map<std::string, std::function<void(void*)>> m_callbackMap;
};

你可以做你想做的事,但不是用字符串而是用类型标签。

这是一个概念证明。

#include <tuple>
#include <utility>
#include <type_traits>

template <typename Tag, std::size_t I, std::size_t N, typename Tup>
struct FMapHelper {
  static constexpr std::size_t helper() {
    if constexpr (I < N) {
      if constexpr (std::is_same_v<typename std::tuple_element_t<I,Tup>::first_type, Tag>) {
        return I;
      } else {
        return FMapHelper<Tag, (I+1), N, Tup>::helper();
      }
    } else {
      return N;
    }
  }
};


template <typename... TFs>
struct FMap {
  std::tuple<TFs...> tfs;

  template <typename Tag, typename F>
  auto more(Tag, F&& f) const {
    return FMap<TFs...,std::pair<Tag,F>>{std::tuple_cat(tfs, std::make_tuple(std::make_pair<Tag,F>(Tag{},std::forward<F>(f))))};
  }

  template <typename Tag>
  auto get() const {
    static constexpr std::size_t I = FMapHelper<Tag, 0, sizeof...(TFs), std::tuple<TFs...>>::helper();
    if constexpr (I < sizeof...(TFs)) {
      return std::get<1>(std::get<I>(tfs));
    } else {
      return nullptr; // no such tag found
    }
  }
};

可以这样使用:

struct tag1 {};
struct tag2 {};

int main() {
  struct Foo {};
  // example functions
  auto const foo = [](Foo const&) { return true; };
  auto const fint = [](int i) { return i*7; };
  
  // example map where e.g. tag1 refers to the foo function
  auto const fmap = FMap<>{}.more(tag1{}, foo).more(tag2{}, fint);

  // exmaple invocation
  fmap.get<tag1>()(Foo{});
  return fmap.get<tag2>()(6);
}

这是一个 live demo 显示,即使仅在 O1 上,编译器也设法完全优化它。