C++将参数包传递给std::map导致错误C3245

C++ pass parameter pack to std::map results in error C3245

本文关键字:map 错误 C3245 std 参数 包传递 C++      更新时间:2023-10-16

我试图调用映射中的函数hold(以实现反射(,并将传递的参数作为参数包,这可能看起来有点奇怪。我无论如何都想让它运行。目前我结束了以下错误:

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)...); }}

您向DoStuff1和DoStuff2转发了3个参数,这不是您想要的。