![](/img/trans.png)
[英]C++ Template - no matching overloaded function found, could not deduce template argument for 'T'
[英]C++ | Could not deduce template argument for T | Void function with no arguments (display() )
我正在C ++中創建帶有模板的動態Que,以供進一步練習。 除了我定義的最后2個功能外,最重要的功能似乎都可以正常工作-沒有參數的void函數。
#include <iostream>
#include <string>
using namespace std;
template <typename T>
class DynamicQueue
{
private:
// Structure for the queue nodes
struct QueueNode
{
T value; // Value in a node
QueueNode *next; // Pointer to the next node
};
QueueNode *top; // The top of the queue
QueueNode *bottom; // The bottom of the queue
int numItems; // Number of items in the queue
public:
DynamicQueue() {
top = nullptr;
bottom = nullptr;
numItems = 0;
}
~DynamicQueue() {
delete[] top;
delete[] bottom;
}
template <typename T>
bool isEmpty() const {
bool empty;
if (numItems > 0)
empty = false;
else
empty = true;
}
template <typename T>
void display() const {
QueueNode* temp = top;
while (temp != nullptr) {
cout << temp->value << endl;
temp=temp->next;
}
}
template <typename T>
void clear() {
T temp;
while (!isEmpty()) {
dequeue(data);
}
}
};
我沒有在代碼中包含enque和deque函數,因為它們工作得很好。 主要功能看起來像:
int main() {
string str;
int number;
DynamicQueue<string> strQ;
DynamicQueue<int> intQ;
strQ.enqueue("Word number 1");
strQ.enqueue("2");
strQ.dequeue("2");
strQ.display();
intQ.enqueue(1);
intQ.enqueue(2);
int placehold;
intQ.dequeue(placehold);
intQ.display();
strQ.clear();
intQ.clear();
getchar();
return 0;
}
編譯器產生以下錯誤:
錯誤C2672:“ DynamicQueue :: display”:找不到匹配的重載函數
錯誤C2783:“無效DynamicQueue :: display(void)const”:無法推斷出“ T”的模板參數
注意:請參見“ DynamicQueue :: display”的聲明
我知道問題出在我做模板錯誤的地方。 但我似乎並不了解正確的做法。
(clear()函數存在相同的問題)
您似乎遇到了模板屏蔽問題,因為您正在通過類方法定義重新聲明模板T ,這在您的情況下是多余的。
如果您在類定義之外實現了方法,那將是必要的。
內部類定義:
void clear() {
// Stuff
}
外:
template <typename T>
void DynamicQueue<T>::clear() {
// Stuff
}
您最初使用的語法是特定於方法的新模板聲明,例如,使它入隊的語法可能是:
template<typename... Args>
void enqueue(Args&&... args)
{
// Create new node
QueueNode* new_node = new QueueNode();
bottom->next = new_node;
new (&(new_node->value)) T(args...);
bottom = new_node;
}
和外部聲明:
template<typename T>
template<typename... Args>
void DynamicQueue<T>::enqueue(Args&&... args)
{
// Create new node
QueueNode* new_node = new QueueNode();
bottom->next = new_node;
new (&(new_node->value)) T(args...);
bottom = new_node;
}
但是模板參數的名稱不能為T,否則會出現陰影問題
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.