Home > Backend Development > C++ > body text

How to Store Functions with Different Signatures in a Map in C ?

Mary-Kate Olsen
Release: 2024-11-14 15:54:02
Original
327 people have browsed it

How to Store Functions with Different Signatures in a Map in C  ?

Storing Functions with Distinct Signatures in a Map

In C , creating a map with string keys and generic functions as values poses a challenge. However, utilizing a combination of type erasure and a templated operator(), this can be achieved.

Type erasure allows the storage of different function types in a single container, while the templated operator() provides access to the stored functions. The code example below demonstrates this approach:

#include <any>
#include <functional>
#include <map>
#include <string>

template<typename Ret>
struct AnyCallable
{
    template<typename ... Args>
    Ret operator()(Args&amp;&amp; ... args) { ... }
    std::any m_any;
};

void foo(int x, int y) { ... }
void bar(std::string x, int y, int z) { ... }

int main()
{
    std::map<std::string, AnyCallable<void>> map;
    map["foo"] = &amp;foo;
    map["bar"] = &amp;bar;
    
    map["foo"](1, 2);
    map["bar"]("Hello", 1, 2);
}
Copy after login

In this solution, the AnyCallable class acts as a wrapper around the stored functions, providing the templated operator(). The function pointers &foo and &bar are converted to std::function objects before being stored in the m_any member. When the stored functions are invoked, they are cast to the appropriate function type and executed.

It's important to note that due to type erasure, matching arguments must be provided at the call site. Furthermore, the const-ness of function arguments is significant, as different overloads may be created with the same number of arguments but different qualifiers.

The above is the detailed content of How to Store Functions with Different 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