我目前正在編程我自己的PriorityQueue
C++中的數據結構,我已將它編入模板類typename T
。根據模板類型在std :: to_string()和.toString()之間切換
我的類的toString()
成員函數被定義爲:
/**
* @brief Gives a std::string representation of this queue structure
*
* The priority queue is returned as a string in the following format:
*
* \code{.cpp}
* Data Item Priority
* [Item] [P1]
* [Item] [P2]
* [Item] [P3]
* \endcode
*
* where P1 < P2 < P3.
*
* @return String representation of this priority queue
*/
std::string toString() const {
std::string tempString = "";
// initialise temporary node to front of priority queue
PQNode<T>* tempNode = front;
// append string with headers
tempString += "Data Item \t\t Priority\n";
// while tempNode is not null, continue appending queue items to string
while (tempNode != nullptr) {
tempString += std::to_string(tempNode->head) + "\t\t\t " + std::to_string(tempNode->priority) + "\n";
// shift tempNode to tail of current tempNode (moving along queue)
tempNode = tempNode->tail;
}
return tempString;
}
我怎樣才能編碼此使得std::to_string()
是在此方法中使用,如果模板的類型是基本如int
或double
和.toString()
(調用傳遞類的toString方法)是否被調用,如果模板的類型是一個具有自己的toString
成員函數的類?
我認爲有一種方法可以用#ifndef
子句做到這一點,但是我沒有太多使用這些的經驗。
嗯,我主要是爲了它的樂趣,練習用C++編寫數據結構(我喜歡保持知識新鮮)以及個人項目我希望比STL版本有更多的優先級隊列功能。感謝您提供的信息,我會仔細研究<<運算符的重載。 – ArchbishopOfBanterbury
這比例很好。我們也很高興看到簡單的SFINAE帶有尾隨返回類型和'decltype'。另一種解決方案:實現非成員的'to_string'重載,然後使用'std :: to_string'做一個ADL +的東西,就像'swap'通常做的那樣。 – juanchopanza
@ArchbishopOfBanterbury:「more functions」聽起來很糟糕。添加更多函數的C++方法就是添加更多的函數:)我的意思是獨立模板函數與迭代器一起工作,就像''中的所有函數一樣,目標是讓函數與*任何可以充當優先隊列的容器類。 –