c++ - 使用模板

标签 c++ templates

我一直在尝试获取一个模板,将字符串中的字符转换为大写字母。

我需要在我的程序中多次执行此操作。

所以我将使用一个模板。

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/

相关文章:

c++ - 如何获得可调用类型的签名?

c++ - 继承一个带有内部类的模板类,并在继承类中访问内部类

c++ - Visual Studio 2013 中的函数模板替换错误?

javascript - 在 Angular JS 中,如何将指令属性中的数据注入(inject)模板?

c++ - 在 win32 控制台应用程序中打印参数

c++ - C++ 的压缩库

c++ - Makefile 目标始终与代码生成保持同步

c++ - 相当于 C/C++ 中的 numpy.nan_to_num

c++ - 为什么当递归函数结果相乘时,g++仍然优化尾递归?

c++ - 模板化类型函数中的模板参数