Home > Backend Development > C++ > How Can You Store Functions with Non-Homogeneous Signatures in a Map in C ?

How Can You Store Functions with Non-Homogeneous Signatures in a Map in C ?

Linda Hamilton
Release: 2024-11-18 07:53:02
Original
258 people have browsed it

How Can You Store Functions with Non-Homogeneous Signatures in a Map in C  ?

Storing Functions with Non-Homogenous Signatures in a Map

Problem Introduction

In C , the need arises to associate functions with different signatures with unique identifiers for dynamic invocation based on runtime arguments. However, the standard containers do not directly support the storage of non-homogenous function types.

Utilizing Type Erasure and Template Operators

One approach to overcome this limitation is type erasure, which involves encapsulating function types into a container that erases specific type information. This allows for the uniform storage of functions with varying signatures. To facilitate this process, a custom data structure, AnyCallable, is defined:

template<typename Ret>
struct AnyCallable
{
    AnyCallable() {}
    template<typename F>
    AnyCallable(F&& fun) : AnyCallable(std::function(std::forward<F>(fun))) {}
    template<typename ... Args>
    AnyCallable(std::function<Ret(Args...)> fun) : m_any(fun) {}
    template<typename ... Args>
    Ret operator()(Args&& ... args) 
    { 
        return std::invoke(std::any_cast<std::function<Ret(Args...)>>(m_any), std::forward<Args>(args)...); 
    }
    std::any m_any;
};
Copy after login

The AnyCallable accepts heterogeneous function types and provides a generic operator() for invoking the encapsulated function with matching arguments.

Example Implementation

Using the AnyCallable data structure, we can now create a map that stores functions with different signatures:

std::map<std::string, AnyCallable<void>> map;
map["foo"] = &foo;
map["bar"] = &bar;
Copy after login

To invoke the functions dynamically based on their unique string identifiers, we utilize the operator() provided by AnyCallable:

map["foo"](1, 2);
map["bar"]("Hello", 1, 2);
Copy after login

This approach ensures type safety and dynamic invocation of functions with non-homogenous signatures, making it a versatile solution for storing and executing method pointers with different inputs.

The above is the detailed content of How Can You Store Functions with Non-Homogeneous Signatures in a Map in C ?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template