C++将参数包传递给std::map导致错误C3245
C++ pass parameter pack to std::map results in error C3245
我试图调用映射中的函数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个参数,这不是您想要的。
相关文章:
- C++将参数包传递给std::map导致错误C3245
- c++:[错误]"map"之前的预期初始值设定项
- 编译器错误 C2664 使用 std::map 和自定义类作为其值
- std::map 擦除 - 将迭代器传递给错误的映射
- 带有 std::map 的模板函数给出错误:变量或字段声明为 void
- 尝试 ptr->map.clear() 时出现分段错误
- 错误:与'operator='不匹配(操作数类型为"std::map<int、double>::iterator
- 使用std :: map时,包含unique_ptr的结构中的默认破坏者会导致编译错误
- 自动,错误:MAP ITERATOR没有名为“ First”的成员
- 将项目插入到std :: map时错误
- 由于从 std::map 派生的类中的 std::map 迭代器导致的内存错误
- 如何在<int>错误 C2338 中组织 map<set<multiset>,int> C++
- 在 std::map 中使用结构作为值时出现运行时错误
- map.insert:"Invalid arguments"错误与 pair<enum,vector<*>>
- SWIG:包装 std::map<key 时编译器错误,val *>
- 使用 std::map 时只读成员的错误递减
- 为什么缩小转换范围不能防止错误类型的map.insert()失败
- 错误 C2062:引用 std::map 时键入意外
- std::map错误的多重定义
- 带有指针的map:错误的值评估