Home > Backend Development > C++ > How can I store functions with varying signatures in a map in C ?

How can I store functions with varying signatures in a map in C ?

Susan Sarandon
Release: 2024-11-19 09:26:03
Original
401 people have browsed it

How can I store functions with varying signatures in a map in C  ?

Storing Functions with Varied Signatures in a Map

In C , you may encounter the need to store functions with varying signatures in a map, where the key is a string and the value is a generic method. While this may initially seem challenging, it's possible with the help of type erasure and a template operator.

Type Erasure

To enable storing functions with different signatures in a map, we first type-erase them into a container. This involves converting the function types into a common representation that can be stored and retrieved from the map.

Template Operator

Once the function types have been type-erased, we provide a template operator () for the map. This operator takes the stored function as input and allows us to call it with specific parameters at runtime. The parameters provided must match the original function signature exactly. If they don't, the operator will throw a std::bad_any_cast exception.

Example

Here's an example of how this can be implemented:

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

template<typename Ret>
struct AnyCallable
{
    //...
};

void foo(int x, int y)
{
    //...
}

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

using namespace std::literals;

int main()
{
    // Initialize the map
    std::map<std::string, AnyCallable<void>> map;

    // Store functions in the map
    map["foo"] = &foo;
    map["bar"] = &bar;

    // Call the stored functions with parameters
    map["foo"](1, 2);
    map["bar"]("Hello, std::string literal"s, 1, 2);
}
Copy after login

In this example, we define a wrapper struct AnyCallable that type-erases functions and provides a template operator () for calling them.

Considerations

  • It's important to note that because of type erasure, you must specify parameters that exactly match the original function signature.
  • If you attempt to call a stored function with mismatched parameters, the operator will throw a std::bad_any_cast exception.

The above is the detailed content of How can I store functions with varying 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