我一直在尝试获取一个模板,将字符串中的字符转换为大写字母。
我需要在我的程序中多次执行此操作。
所以我将使用一个模板。
template <string theString>
string strUpper( string theString )
{
int myLength = theString.length();
for( int sIndex=0; sIndex < myLength; sIndex++ )
{
if ( 97 <= theString[sIndex] && theString[sIndex] <= 122 )
{
theString[sIndex] -= 32;
}
}
return theString;
}
现在只有模板有效! 有什么建议么? “字符串”标识符应该是一个直接标志。
最佳答案
你显然在谈论 C++
(还没有标签,所以我认为这里是 C++)。嗯,你好像想说
As arguments to my template, i accept any type that models a string
遗憾的是,目前还不可能。它需要 concept
将在下一个 C++ 版本中的功能。 Here是关于他们的视频。
你能做的就是接受 basic_string<CharT, TraitsT>
如果你想保持它的通用性,例如,如果你想接受宽字符串和窄字符串
template <typename CharT, typename TraitsT>
std::basic_string<CharT, TraitsT> strUpper(basic_string<CharT, TraitsT> theString ) {
typedef basic_string<CharT, TraitsT> StringT;
for(typename StringT::iterator it = theString.begin();
it != theString.end();
++it)
{
*it = std::toupper(*it, std::locale());
}
return theString;
}
它不会接受恰好也是 strings 的其他或自定义字符串类。如果你想要那样,让它完全摆脱它接受和不接受的东西
template <typename StringT>
StringT strUpper(StringT theString) {
for(typename StringT::iterator it = theString.begin();
it != theString.end();
++it)
{
*it = std::toupper(*it, std::locale());
}
return theString;
}
您必须告诉该库的用户他们必须公开哪些函数和类型才能使其正常工作。编译器将不知道该契约(Contract)。相反,当使用非字符串类型调用函数时,它只会抛出错误消息。通常,您会发现错误消息的页面,并且很难找到出错的真正原因。为下一版本的标准提出的概念功能很好地解决了这个问题。
如果您不打算编写这样一个通用函数,您可以继续编写一个像这样的普通函数
std::string strUpper(std::string theString) {
for(std::string::iterator it = theString.begin();
it != theString.end();
++it)
{
*it = std::toupper(*it, std::locale());
}
return theString;
}
如果您一开始不打算发明那个函数来学习,但是因为您没有找到另一个已经编写好的算法,请查看 boost string algorithm图书馆。然后你可以写
boost::algorithm::to_upper(mystring);
关于c++ - 使用模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/645432/