如何修复"没有重载函数需要 2 个参数"错误C++

How to fix 'no overloaded function takes 2 arguments' error C++

本文关键字:参数 错误 C++ 函数 何修复 重载      更新时间:2023-10-16

我正在尝试为哈希表创建一个类以包含唯一指针,但是每当我尝试添加指向该表的指针时,我都会收到一个错误,该错误指向我正在使用的库中的不同文件。

我尝试使用.insert()而不是.emplace().我试过传入一对钥匙和指针。

这两者都导致了与原始错误不同的错误

这是Hash_Table类:

///<summary>
/// A struct for a hash table
///</summary>
template <typename T>
struct Hash_Table
{
public:
///<summary>
/// Add an item to the hash table & return the item key
///</summary>
int addItem(T newItem) {
// Make the item into a unique pointer
std::unique_ptr<T> itemPtr = std::make_unique<T>(newItem);
//std::pair<int, std::unique_ptr<T>> pair = std::make_pair(tailPointer, itemPtr);
while (!Table.emplace(tailPointer, itemPtr).second) {
tailPointer++;
//pair.first++;
}
tailPointer++;
return tailPointer--;
};
private:
///<summary>
/// The actual hash table
///</summary>
std::unordered_map<int, std::unique_ptr<T>> Table;
///<summary>
/// Points to the key of the last item added to the hash table
///</summary>
int tailPointer;
};

当我尝试table.emplace()addItem()函数中发生了问题。

如上所示,文件内存中的代码错误:

C2661: '标准::p空气::p空气':无过载函数 需要 2 个参数

使用table.insert()时文件哈希表.h 中的错误:

C2664: 'std::_List_iterator>>std::_Hash>,std::_Uhash_compare<_Kty,_Hasher,_Keyeq>,_Alloc,false>>:::insert(std::_List_const_iterator>>,const std::p air>>&(':无法将参数 1 从 'int' 转换为 "标准::_List_const_iterator>>">

使用table.inserttable.emplace(std::make_pair(tailPointer, itemPtr))时文件实用程序中的错误:

C2440:":无法从"初始值设定项列表"转换 到"_MyPair">

多种解决问题的方法:

解决方案 1:

int addItem(T newItem) {
// Make the item into a unique pointer
std::unique_ptr<T> itemPtr = std::make_unique<T>(newItem);
// Unique_ptr doesn't have assignment operator instead it has move-assignment.
// So it need to be moved only
std::pair<int, std::unique_ptr<T>> pair = std::make_pair(tailPointer++, std::move(itemPtr));
// For same above reason, it must be moved
Table.insert(std::move(pair));
return tailPointer;
};

解决方案 2:

int addItem(T newItem) {
Table.insert(std::make_pair(tailPointer++, std::make_unique<T>(newItem)));
return tailPointer;
}

解决方案 3:

int addItem(T newItem) {
Table[tailPointer++] = std::make_unique<T>(newItem);
return tailPointer;
}

上述解决方案都不需要C++ 17。所有这些都来自C++11。您应该了解为什么会出现编译错误。使用现有代码,您正在尝试分配或复制不允许的unique_ptr。它只能被移动。这就是编译器试图告诉您的。

谢谢Jarod42,您的修复确实有效。

修复:Table.emplace(tailPointer, itemPtr)->Table.try_emplace(tailPointer, std::move(itemPtr))(但C++17(。 - 贾罗德42

使用它,将解决 c++11 中的unique_ptr问题

int addItem(T newItem) {    
// Make the item into a unique pointer
while (!Table.emplace_hint(tailPointer, newItem).second) {
tailPointer++;
//pair.first++;
}
tailPointer++;
return tailPointer--;
};