c++ - 如何在 C++ 中创建将函数与参数相关联的映射?

标签 c++

假设您想顺序调用 100 个函数。

我想创建一个包含函数指针和函数参数的映射,以便我可以迭代该映射并使用关联的参数调用每个函数。

参数具有不同的类型、元数和返回类型。是否可以在 C++ 中实现这样的映射?

伪代码

for function in map
    // call the function with the arguments from the map
    function(map[function]) 

最佳答案

如评论中所述,这个问题太宽泛了。因此,可能的解决方案太多了。另外,我真的很想知道你为什么需要这种功能图。我敢肯定,如果您解释了您的问题,许多人会建议您采用不同的解决方案。

也就是说,我发现这个主题很有趣,并尝试对您的问题实现可能的解决方案。

由于主题非常广泛,问题不够具体,我不得不做出一些决定(也是基于评论):

  • 我使用了 set 而不是 map 因为我不知道 map 的(键,值)应该是什么。
  • 我只是打印出结果(假设结果是可打印的),因为我不知道如何处理结果。
  • 我没有使用函数指针,而是使用了函数对象。
  • 由于我无法完全理解伪代码,这些函数由调用函数调用。

修改下面的示例代码应该可以让您得到您真正想要的。以下代码只是您可能需要哪种成分的示例。

GenericFunction 和集合

您只能在set(或map)中保存一种类型,因此您需要一些GenericFunction 类:

class GenericFunction
{
public:
    virtual ~GenericFunction() = default;

    virtual void invoke() const = 0; // the method to invoke the function
};

现在,您可以定义一个 set,它将包含指向 GenericFunction 对象的指针:

std::set<GenericFunction*> myFcts;

具体功能类

接下来,让我们实现派生自GenericFunction类的具体函数类。此类的目标是存储您选择的函数和参数,并提供 invoke 函数的实现。

#include <iostream>
#include <tuple>

template <typename Fct, typename ... Args>
class MyFct : public GenericFunction
{
public:
    MyFct(Fct fct, Args&& ... args) :
        _fct { std::move(fct) },
        _args { std::forward<Args>(args)... }
    {}

    void invoke() const override { std::cout << std::apply(_fct,_args) << std::endl; }

private:
    Fct _fct;
    std::tuple<Args ...> _args;
};

测试:求和函数

为了测试,让我们编写一个简单的求和函数:

template <typename T>
auto sum(T a)
{
    return a;
}

template <typename F, typename ... R>
auto sum(F first, R ... rest)
{
    return first + sum(rest...);
}

主要功能

我们现在可以像这样使用上面的代码:

#include <set>

int main()
{
    // function wrapper
    auto sum_wrapper = [](auto&&... args)
    {
        return sum(std::forward<decltype(args)>(args)...);
    };

    // create a specific function
    MyFct myf1(sum_wrapper, 1, 2.33/*, add the args of your choice*/);

    // create another specific function        
    MyFct myf2(sum_wrapper, 10, 2.33/*, add the args of your choice*/);

    // create the set
    std::set<GenericFunction*> myFcts { &myf1, &myf2 };

    // call the functions
    for (const auto& f : myFcts)
        f->invoke();

    return 0;
}

关于c++ - 如何在 C++ 中创建将函数与参数相关联的映射?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57253595/

相关文章:

C++ Qt QTableWidget 项目在调整列大小时移动

c++ - Eclipse 中的新 .h 文件产生一个#define 常量

c++ - 如何将 herader 从二进制数据中分离出来

c++ - C++ 中的 3x3 矩阵旋转

c++ - 用qt从postgres读写图像(大对象)

c++ - QNetworkReply::NetworkError(ProtocolInvalidOperationError) 它是什么以及如何修复它?

c++ - 使用水平滚动条手动设置 MFC CComboBox 下拉高度

c++ - 并行测试与 geos 的交集时出现段错误

c++ - 使用 OpenGL 无法正确显示三角形带

c++ 20如何制作一个像容器一样的约束元组,它只包含允许的类型和它自己的一个实例