简体   繁体   English

C ++仅在模板为字符串类型时才执行toLowercase转换

[英]C++ Only execute toLowercase conversion when template is of type string

Good day, 美好的一天,

I am writing a simple C++ Linked List using templates. 我正在使用模板编写一个简单的C ++链表。 I have got everything working, but I wanted to add to the functionality by making it case insensitive by converting all characters to lowercase for when the template is of type string. 我已完成所有工作,但我想通过在模板为字符串类型时将所有字符都转换为小写使其不区分大小写来增加功能。

So, I wrote the following snippet to handle any word and convert it to all lower cases: 因此,我编写了以下代码片段来处理任何单词并将其转换为所有小写字母:

        #define TEMPLATE string // changing this changes the template type in the rest of the program
        Stack <TEMPLATE> s; //not used in this example, but just to show that I have an actual template for a class declared at some point, not just a definition called TEMPLATE
        TEMPLATE word; // User inputs a word that is the same type of the Linked List Stack to compare if it is in the Stack.
        cin >> word; // just showing that user defines word
        for (unsigned int i = 0; i < word.length(); i++)
        {
            if (word.at(i) >= 'A' && word.at(i) <= 'Z')
                word.at(i) += 'a' - 'A';
        }

The problem is that when the TEMPLATE of my Stack, and subsequently the compared word to the stack is not of type string, then it obviously throws error messages because the for loop was written specifically to look at strings. 问题是,当我的堆栈的TEMPLATE以及随后与堆栈进行比较的单词不是字符串类型时,它显然会引发错误消息,因为for循环是专门为查看字符串而编写的。

So, is there a way I could make this function more generic so that any type can be passed? 那么,有没有一种方法可以使此函数更通用,以便可以传递任何类型? (I don't think so, since there would be no error checking for ints, etc. String is the only one that relies on this) (我不这样认为,因为不会对int等进行错误检查。String是唯一依赖于此的字符串)

Or, is there a way that I can only execute the above code when my Template for my Stack and compared variable is of type string? 或者,有没有一种方法只能在我的Stack模板和比较变量的类型为string时执行以上代码?

I looked at exception handling, except I'm very much used to how Python works and so I could not figure out exactly how to implement in C++ instead. 我研究了异常处理,只是我非常熟悉Python的工作方式,因此我无法确切地知道如何在C ++中实现。

Just as a side note, I am not using any built in functions to convert the string to all lower cases, so that is not an option either and I am not looking for recommendations of those. 只是附带说明,我没有使用任何内置函数将字符串转换为所有小写字母,因此也不是一种选择,我也没有在寻找这些建议。

Create overloads to normalize your data: 创建重载以规范化数据:

std::string normalize(const std::string& s) {
    std::string res(s);
    for (auto& c : res) {
        c = std::tolower(c);
    }
    return res;
}

template <typename T>
const T& normalize(const T& t) { return t; }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM