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

标签 c++ string templates c++11

我目前正在用 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/

相关文章:

python - Bottle.py 缓存模板,尽管处于 Debug模式

c++ - 将对象传递给以指针为参数的函数

c++ - 对齐 QCheckbox 文本和它下面的 QLabel

python - 如何将 f-string 与变量一起使用,而不是与字符串文字一起使用?

c++ - 在计算类型后省略参数名称

c++ - 'using'指令如何与模板成员函数一起工作

c++ - 复制构造函数中的递归调用

c++ - 如何从多个 std::threads 手动发送 QSignal?

ios - 快速迭代字符长度

ruby-on-rails - ruby 数组中的字符串替换