再会,
我正在使用模板编写一个简单的 C++ 链表。我已经完成了所有工作,但是我想通过在模板为字符串类型时将所有字符转换为小写来使其不区分大小写来添加功能。
因此,我编写了以下代码片段来处理任何单词并将其转换为所有小写:
#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';
}
问题是,当我的堆栈的模板以及随后与堆栈比较的单词不是字符串类型时,它显然会抛出错误消息,因为 for 循环是专门为查看字符串而编写的。
那么,有没有办法让这个函数更通用,以便可以传递任何类型?(我不这么认为,因为不会对整数等进行错误检查。字符串是唯一依赖于此的)
或者,当我的 Stack 和比较变量的模板是字符串类型时,我是否只能执行上述代码?
我研究了异常处理,但我非常习惯 Python 的工作方式,所以我无法确切地弄清楚如何在 C++ 中实现。
顺便说一句,我没有使用任何内置函数将字符串转换为所有小写字母,因此这也不是一个选项,我也不是在寻找这些建议。