空std::function
并不那么重。你可以映射到一个包含每个结构的结构。你知道哪个是有效的,所以只能访问那个。
如果您有需要,而不在任一作为参数传递上都均匀工作模板代码:
#include <string>
#include <functional>
#include <map>
#include <tuple>
#include <iostream>
#include <math.h>
template<typename T>
using my_maps = std::tuple< std::map<std::string, std::function<T()>>, std::map<std::string, std::function<T(int)>>>;
int main() {
my_maps<double> maps;
std::get<0>(maps)["pi"] = [](){ return 3.14; };
std::get<1>(maps)["e^"] = [](int x){ return pow(2.7, x); };
std::cout << std::get<1>(maps)["e^"](2) << "\n";
std::cout << std::get<0>(maps)["pi"]() << "\n";
}
这有两张地图,在访问get<0>
或get<1>
的差异。这样做的好处是,如果您正在选择要在模板中访问哪两个模块,它可以静态选择0或1,并使用通用代码。如果你不需要这个,只需要两个std::map
。
A boost::variant
也有效(映射到0ary或1ary函数的variant
)。你也可以在带有枚举的struct
中使用C++ 11 union
(注意它将没有默认构造函数,或者复制构造函数,除非你提供一个), - 基本上是一个枚举(它的副本为union
)贫民窟boost::variant
。
@OliCharlesworth,这是一种出路!在某些时候,我希望能够隐藏这个,例如,只有一个获得地图类的方法。但我当然可以解决它。 –
为什么不只是有两个容器?由于无论如何您必须进行一些检查,因此您知道如何调用函数,您还可以通过分隔两种函数来进行检查。 –