我尝试调用传递给参数的参数包中的函数(以实现反射),该函数保留在映射中,这看起来可能有些奇怪。我想让它继续运行。目前,我遇到以下错误:
main.cpp(36): error C3245: 'funcMapA': use of a variable template requires template argument list
main.cpp(23): note: see declaration of 'funcMapA'
这是我的最低要求(不适用):
#include <functional>
#include <map>
#include <string>
#include <sstream>
#include <iostream>
#include <iterator>
#include <vector>
#include <utility>
void DoStuff_1(int i) {
std::cout << "DoStuff_1 " << i << "\n";
}
void DoStuff_2(int i, int k) {
std::cout << "DoStuff_2 " << i << ", " << k << "\n";
}
void DoStuff_3(int i, int k, int l) {
std::cout << "DoStuff_3 " << i << ", " << k << ", " << l << "\n";
}
template <typename ... Ts>
std::map<std::string, std::function<void(Ts&& ... args)>> funcMapA = {
{"DoStuff_1", [](Ts&& ... args) {DoStuff_1(std::forward<Ts>(args)...); }},
{"DoStuff_2", [](Ts&& ... args) {DoStuff_2(std::forward<Ts>(args)...); }},
{"DoStuff_3", [](Ts&& ... args) {DoStuff_3(std::forward<Ts>(args)...); }}
};
std::map<std::string, std::function<void(int, int, int)>> funcMapB = {
{"DoStuff_1", [](int x, int y, int z) {DoStuff_1(x); }},
{"DoStuff_2", [](int x, int y, int z) {DoStuff_2(x, y); }},
{"DoStuff_3", [](int x, int y, int z) {DoStuff_3(x, y, z); }}
};
int main(int argc, char** argv) {
funcMapA["DoStuff_" + std::to_string(3)](1, 2, 3); //Failing
funcMapB["DoStuff_" + std::to_string(3)](1, 2, 3); //Working
getchar();
return 0;
}
如何使此(funcMapA)正常工作?
有两个问题:
首先:您必须提供这样的模板参数:
funcMapA<int,int,int>["DoStuff_" + std::to_string(3)](1, 2, 3);
第二:但是,如果这样做,您的模板实现将失败,因为:
{"DoStuff_1", [](Ts&& ... args) {DoStuff_1(std::forward<Ts>(args)...); }},
{"DoStuff_2", [](Ts&& ... args) {DoStuff_2(std::forward<Ts>(args)...); }},
{"DoStuff_3", [](Ts&& ... args) {DoStuff_3(std::forward<Ts>(args)...); }}
您将3个参数转发给DoStuff1和DoStuff2,这不是您想要的。