从unordered_multimap中从另一个类调用函数?

Calling a function from another class from within an unordered_multimap?

本文关键字:调用 函数 unordered multimap 另一个      更新时间:2023-10-16

这与我的上一篇文章有关,你可以在这里找到:使用任何参数创建 std::functions 的unordered_map。我现在已经把它扩展到课堂上。假设我有三个不同的班级。而且这些类除了getVariable()setVariable(int)之外,都有不同的方法。因此,对于此示例,我们将它们分类ClassAClassBClassC

我还有一个基类,我想将其用作驱动程序。本质上,如果我想在ClassAClassC之间设置变量,我会调用基类的setVariable函数。

#ifndef BASE_CLASS_HPP
#define BASE_CLASS_HPP
#include <unordered_map>
#include <functional>
#include <utility>
#include <string>
#include <any>
template<class A, class B>
class BaseClass
{
public:
BaseClass() { bindThem(); }
std::pair<int,int> getValue()
{
// return classA and ClassB's values
}
void setValue(int newVal)
{
auto iter = functions.equal_range("setValue");
std::any_cast<void(*)(int)>(mapIter->second)(newVal);
}
private:
std::unordered_multimap<std::string,std::any> functions;
void bindThem()
{
functions.emplace("setValue",&A::setValue);
functions.emplace("setValue",&B::setValue);
functions.emplace("getValue",&A::getValue);
functions.emplace("getValue",&B::getValue);
}
};

然后我主要有:

#include <iostream>
#include "baseClass.hpp"
#include "classA.hpp"
#include "classB.hpp"
#include "classC.hpp"
int main()
{
ClassA a;
ClassB b;
ClassC c;
c.setValue(20);
BaseClass<ClassA,ClassB> base1;
BaseClass<ClassA,ClassC> base2;
base1.setValue(15);
auto values = base1.getValues();

}

我可以将函数放置在我的地图中,但是,当我尝试any_cast时,我没有得到任何回报。我也试过:

std::any_cast<void(A::*)(int)>(mapIter->second)(newVal);

但这也给了我一个编译器错误,必须使用 .* 或 ->*,我已经尝试了一切来编译它,但我真的不知道我做错了什么。我还意识到,如果我这样称呼它,那么我将无法访问 B 的setVariable函数,因为我使用的是A's命名空间。

无论如何,我可以让它按照我想要的方式工作吗?我本质上是在尝试修改这些类值,而不必制作这些类的任何副本,而是直接从此驱动程序中修改它们。

我仍然不太明白这种结构的目的,但这里有一个选项如何使其至少编译:

#include <unordered_map>
#include <functional>
#include <utility>
#include <string>
#include <any>
template<class A, class B>
class BaseClass
{
public:
BaseClass() { bindThem(); }
std::pair<int,int> getValue()
{
auto range = functions.equal_range("getValue");
return 
{
(a.*std::any_cast<int(A::*)()>(*range.first))(),
(b.*std::any_cast<int(B::*)()>(*range.second))()
};
}
void setValue(int newVal)
{
auto range = functions.equal_range("setValue");
(a.*std::any_cast<void(A::*)(int)>(*range.first))(newVal);
(b.*std::any_cast<void(B::*)(int)>(*range.second))(newVal);
}
private:
std::unordered_multimap<std::string,std::any> functions;
void bindThem()
{
functions.emplace("setValue",&A::setValue);
functions.emplace("setValue",&B::setValue);
functions.emplace("getValue",&A::getValue);
functions.emplace("getValue",&B::getValue);
}
A a;
B b;
};
class ClassA
{
public:
void setValue(int){}
int getValue() {return 0;}
};
class ClassB
{
public:
void setValue(int){}
int getValue() {return 1;}
};
int main()
{
BaseClass<ClassA, ClassB> x;
x.setValue(3);
auto i = x.getValue();
}

请注意以下几点:

  1. 我已经将成员添加到 BaseClass,因为要调用成员函数,您需要调用一个对象。
  2. 我正在使用equal_range范围内的第一个和最后一个迭代器,但该范围内元素的顺序是实现定义的。因此,为了使事情正常工作,您需要注意区分哪个容器元素对应于类A,哪个对应于类B