我有USB设备。我有
std::unordered_map<int, std::unordered_map<int, std::unique_ptr<deviceTypeX>>> deviceTypeXMap;
存储我为设备创建的实例。
类层次结构类似于usbdevice-deviceTypeX-specificDevice
因此每个specificDevice都是-deviceTypeX
deviceTypeX包含specificDevice需要实现的虚函数。 usbdevice包含所有(我)设备共有的通用USB东西,例如连接方法等。
我们的想法是,包含以上各项的类(我们将其称为实例“ usbdevices”)将具有允许写入硬件的公共方法,以便将所有内容抽象化。
在“ usbdevices”头文件中有以下模板:
template <typename classType>
void addInstance(std::unordered_map<int, std::unordered_map<int, std::unique_ptr<classType>>> &outer,
int outerKey, std::unique_ptr<classType> instanceToAdd, int innerKey) {
auto outerSearch = outer.find(outerKey);
if (outerSearch != outer.end()) {
outerSearch->second.try_emplace(innerKey, std::move(instanceToAdd));
}
else{ //outer key not found }
}
添加实例。 像这样发生热插拔事件后,我会使用回调添加它们
addInstance(deviceTypeXMap, desc.idVendor, std::make_unique<specificDevice>(dev, ctx), desc.idProduct);
编译失败,
在... / hardware / usbdevices.cpp:5:0中包含的文件中: ... / hardware / usbdevices.h:47:10:注意:候选:模板无效usbdevices :: addInstance(std :: unordered_map>>&,int,std :: unique_ptr <_Tp>,int) void addInstance(std :: unordered_map >>&outer, ^ ~~~~~~~~~~~ ... / hardware / usbdevices.h:47:10:注意:模板参数推导/替换失败: ... / hardware / usbdevices.cpp:121:114:注意:推导了参数“ _Tp”(“ deviceTypeX”和“ specificDevice”)的冲突类型
为什么specificDevice和deviceTypeX冲突?我正在学习模板...如果我不使用模板,但是很明显我需要模板,那么所描述的方法会起作用,因为否则我将不得不为deviceTypeX,deviceTypeY等创建多个addInstance方法。
我不明白。我需要做些什么才能使其正常工作?
答案 0 :(得分:1)
C ++模板仅匹配给定的 exact 类型,而不会尝试查找兼容的类型。这是错误的原因-deduced conflicting types for parameter ‘_Tp’ (‘deviceTypeX’ and ‘specificDevice’)
。
要解决此问题,您可以使函数采用2个模板参数:
template <typename outerType, typename instanceType>
void addInstance(std::unordered_map<int, std::unordered_map<int, std::unique_ptr<outerType>>> &outer,
int outerKey, std::unique_ptr<instanceType> instanceToAdd, int innerKey) {
auto outerSearch = outer.find(outerKey);
if (outerSearch != outer.end()) {
outerSearch->second.try_emplace(innerKey, std::move(instanceToAdd));
}
else{ //outer key not found }
}
将instanceToAdd
放在函数主体中时将对其进行转换。