自定义C++ trim函数出现的小问题

来源:互联网 发布:编程语言应用领域 编辑:程序博客网 时间:2024/06/05 07:04

在地址

http://blog.csdn.net/butterfly_dreaming/article/details/10142443

中,关于trim函数的方法3:gcc编译器不能通过问题。

       这是该代码:

/* Filename : stringTrim1.cppCompiler : Visual C++ 8.0Description : Demo how to trim string by other method.Release : 11/18/2006*/#include <string>#include <iostream>#include <cwctype>template <class T>std::basic_string<T>& trim(std::basic_string<T>&);int main( ) {    std::string s = " Hello World!! ";    std::cout << s << " size:" << s.size() << std::endl;    std::cout << trim(s) << " size:" << trim(s).size() << std::endl;    return 0;}template <class T>std::basic_string<T>& trim(std::basic_string<T>& s) {    if (s.empty()) {        return s;  }    std::basic_string<T>::iterator c;    // Erase whitespace before the string    for (c = s.begin(); c != s.end() && iswspace(*c++);); s.erase(s.begin(), --c);    // Erase whitespace after the string    for (c = s.end(); c != s.begin() && iswspace(*--c);); s.erase(++c, s.end());    return s;}

以下是我在gcc编译的结果:{环境   gcc version 4.4.6 20120305 (Red Hat 4.4.6-4) (GCC)}   ps:我用的是trim.cpp

[root@localhost testConfig]# g++ trim.cpp
trim.cpp: In function ‘std::basic_string<_CharT, std::char_traits<_CharT>, std::allocator<_CharT> >& trim(std::basic_string<_CharT, std::char_traits<_CharT>, std::allocator<_CharT> >&)’:
trim.cpp:21: error: expected ‘;’ before ‘c’
trim.cpp:23: error: ‘c’ was not declared in this scope
trim.cpp: In function ‘std::basic_string<_CharT, std::char_traits<_CharT>, std::allocator<_CharT> >& trim(std::basic_string<_CharT, std::char_traits<_CharT>, std::allocator<_CharT> >&) [with T = char]’:
trim.cpp:11:   instantiated from here
trim.cpp:17: error: could not convert ‘s->std::basic_string<_CharT, _Traits, _Alloc>::empty [with _CharT = char, _Traits = std::char_traits<char>, _Alloc = std::allocator<char>]’ to ‘bool’
trim.cpp:21: error: dependent-name ‘std::basic_string::iterator’ is parsed as a non-type, but instantiation yields a type
trim.cpp:21: note: say ‘typename std::basic_string::iterator’ if a type is meant


这里报的是“变量c之前丢失分号”的错误,这其实是个误导性的提示,重要的提示是我划线的这两句。一开始很迷惑,看了这个博文

http://blog.sina.com.cn/s/blog_69d9bff30101cx8f.html

后,明白是歧义造成的。gcc编译器并不清楚std::basic_string<T>::iterator是一种类型还是std::basic<T>的成员,除非显示声明其为一个类型,因此直接加上typename关键字就行了。下面是更正后的代码。

trim.cpp

#include <iostream>#include <string>template <typename T>std::basic_string<T>& trim(std::basic_string<T>& s);int main(int argc, char* []) {std::string str = "   hello world    ";std::cout << "before:" << str << std::endl;trim(str);std::cout << "after:" << str << std::endl;return 0;}template <typename T>std::basic_string<T>& trim(std::basic_string<T>& s) {if (s.empty()) {return s;}typename std::basic_string<T>::iterator c;//c;for (c = s.begin(); c != s.end() && iswspace(*c++); );s.erase(s.begin(), --c);for (c = s.end(); c != s.begin() && iswspace(*--c); );s.erase(++c, s.end());return s;}
                                             
0 0
原创粉丝点击