[英]How do you create an array of member function pointers with arguments?
I am trying to create a jump table for a fuzzy controller. 我正在尝试为模糊控制器创建跳转表。 Basically, I have a lot of functions that take in a string and return a float, and I want to be able to do something along the lines: 基本上,我有很多函数可以接收字符串并返回浮点数,并且我希望能够执行以下操作:
float Defuzzify(std::string varName, DefuzzificationMethod defuzz)
{
return functions[defuzz](varName);
}
where DefuzzificationMethod is an enum. 其中DefuzzificationMethod是一个枚举。 The objective is to avoid a switch statement and have a O(1) operation. 目的是避免使用switch语句并进行O(1)操作。
What I have right now is: 我现在所拥有的是:
float CenterOfGravity(std::string varName);
std::vector<std::function<float (std::string)>> defuzzifiers;
Then I try to initialize it in the constructor with: 然后,我尝试使用以下方法在构造函数中对其进行初始化:
defuzzifiers.reserve(NUMBER_OF_DEFUZZIFICATION_METHODS);
defuzzifiers[DEFUZZ_COG] = std::bind(&CenterOfGravity, std::placeholders::_1);
This is making the compiler throw about 100 errors about enable_if (which I don't use anywhere, so I assume std does). 这使编译器抛出关于enable_if的大约100个错误(我在任何地方都没有使用过,因此我假设std会使用)。 Is there a way to make this compile ? 有没有办法进行编译? Moreover, is there a way to make this a static vector, since every fuzzy controller will essentially have the same vector ? 此外,由于每个模糊控制器本质上都具有相同的矢量,有没有办法使它成为静态矢量?
Thanks in advance 提前致谢
Reserve just makes sure there's enough capacity, it doesn't actually mak the vector's size big enough. 保留只是确保有足够的容量,实际上并没有使向量的大小变大。 What you want to do is: 您想要做的是:
// construct a vector of the correct size
std::vector<std::function<float (std::string)>> defuzzifiers(NUMBER_OF_DEFUZZIFICATION_METHODS);
// now assign into it...
// if CentorOfGravity is a free function, just simple = works
defuzzifiers[DEFUZZ_COG] = CenterOfGravity;
// if it's a method
defuzzifiers[DEFUZZ_COG] = std::bind(&ThisType::CenterOfGravity, this, std::placeholders::_1);
Now this might leave you some holes which don't actually have a function defined, so maybe you want to provide a default function of sorts, which the vector constructor allows too 现在,这可能会给您留下一些实际上没有定义函数的漏洞,因此也许您想提供默认的sorts函数,向量构造函数也允许
std::vector<std::function<float (std::string)>> defuzzifiers(
NUMBER_OF_DEFUZZIFICATION_METHODS,
[](std::string x) { return 0f; }
);
An unrelated note, you probably want your functions to take strings by const-ref and not by value, as copying strings is expensive. 一个不相关的说明,您可能希望函数使用const-ref而不是值来获取字符串,因为复制字符串非常昂贵。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.