模板化函数中的比较

comparison in templated function

本文关键字:比较 函数      更新时间:2023-10-16

我正在编写一个模板化函数,该函数在某些时候会进行比较

template<typename T>
void Foo(T val)
{
    .
    .
    .
    if(val != 0) // what if val is of type std::string?
    {
        doSomething();
    }
}

这适用于整数数据,但如果 T 是 std::string 怎么办?我应该如何处理这种情况,以便我可以在函数中同时使用 std::string 和 int?

编辑:忽略我在下面键入的所有内容,只使用模板专用化。

如果您还必须考虑字符串的可能性,则必须构建另一个函数来处理这些字符串,因为比较是不同的,使用函数重载而不是尝试使用处理整数、浮点数、双精度数等的模板编译它。您可以使用.compare(anotherstring or "") == 0 .empty() .length() == 0 .如果您不熟悉这三个标准操作,我建议您阅读它们。您的字符串处理函数如下所示(取决于哪个子句最适合您的情况(:

void Foo(std::string val)
{
    .
    .
    .
    if (val.length() == 0) {
        std::cout << "string is of 0 lengthn";
    } else {
        std::cout << "string is of " << thing.length() << " lengthn";
    }

    if (val.compare("") == 0) {
        std::cout << "string is a blank stringn";
    } else {
        std::cout << "string is not a blank stringn";
    }
    if (val.empty()) {
        std::cout << "string is emptyn";
    } else {
        std::cout << "string is not emptyn";
    }
}

您甚至可以将它们全部or在一个短路的大检查器中,并且不会继续检查第一个是否为真,尽管这在某些情况下可能是多余的。像这样:

if (val.compare("") == 0 || val.length == 0 || val.empty()) { doSomething(); }

希望这有帮助和快乐的编码