gpt4 book ai didi

c++ - 根据模板类型在 std::to_string() 和 .toString() 之间切换

转载 作者:太空狗 更新时间:2023-10-29 23:49:57 25 4
gpt4 key购买 nike

我目前正在用 C++ 编写我自己的 PriorityQueue 数据结构,我已经将其制作成一个带有 typename T 的模板类。

我的类的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;

}

如果模板的类型是原语,如 intdouble.toString()(调用传递类的 toString 方法)如果模板的类型是一个有自己的 toString 的类,则调用> 成员函数?

我想有一种方法可以使用 #ifndef 子句来实现,但是我没有太多使用这些的经验。

最佳答案

首先,当有 std::priority_queue 时,为什么要这样做? ?

其次,toString 通常是设计错误成员函数,因为它将数据逻辑与数据表示硬连接起来。你应该做的是重载 operator<<对于您的类(class),您可以将实例传递给任何 std::ostream .

第三,您要求的是在编译时根据类型是否具有 toString 选择“正确的”字符串转换函数。成员函数,并使用 std::to_string作为后备。这可以在 C++11 中通过一些模板和 auto 很好地实现。魔法。这是一个例子:

#include <string>
#include <iostream>

struct Example
{
std::string toString() const { return "foo"; }
};

template <class T>
auto ToString(T const& t) -> decltype(t.toString())
{
std::cout << "Using toString\n";
return t.toString();
}

template <class T>
auto ToString(T const& t) -> decltype(std::to_string(t))
{
std::cout << "Using std::to_string\n";
return std::to_string(t);
}

int main()
{
Example e;
std::cout << ToString(e) << "\n";

int i = 0;
std::cout << ToString(i) << "\n";
}

输出:

Using toString
foo
Using std::to_string
0

另见 C++11 ways of finding if a type has member function or supports operator? (尤其是用户“zah”的回答)。


不过,我强烈建议实现 operator<<方法。

关于c++ - 根据模板类型在 std::to_string() 和 .toString() 之间切换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35182985/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com