我一直在尝试获取一个模板,将字符串中的字符转换为大写字母.
我需要在整个程序中多次这样做.
所以我会使用一个模板.
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;
}
Run Code Online (Sandbox Code Playgroud)
现在只有模板有效!有什么建议?'string'标识符应该是立即标志.
你显然在谈论C++(还没有标签,所以我认为这是C++).好吧,你似乎想说
作为我的模板的参数,我接受任何模拟字符串的类型
可悲的是,目前还不可能.它需要concept将在下一个C++版本中的功能.这是关于他们的视频.
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;
}
Run Code Online (Sandbox Code Playgroud)
它也不会接受恰好是字符串的其他或自定义字符串类.如果你想要的话,那就让它完全不受它接受和不接受的东西的影响
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;
}
Run Code Online (Sandbox Code Playgroud)
您必须告诉该库的用户他们必须公开哪些功能和类型才能使其工作.编译器不会知道该合同.相反,当调用具有非字符串类型的函数时,它只会抛出错误消息.通常,您会发现错误消息的页面,并且很难找到出错的真正原因.提议的概念功能可以很好地用于下一版本的标准修复.
如果您不打算编写这样的通用函数,您可以继续编写这样的普通函数
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;
}
Run Code Online (Sandbox Code Playgroud)
如果您不打算首先发明该函数来学习,但由于您没有找到另一个已编写的算法,请查看boost 字符串算法库.然后你就可以写了
boost::algorithm::to_upper(mystring);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
145 次 |
| 最近记录: |