Last active
August 29, 2015 14:00
-
-
Save aaronj1335/11219461 to your computer and use it in GitHub Desktop.
why can't i return a non-const string from line_iterator::dereference() (line 32). if i change it to `const string& dereference() const` it compiles.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
astacy∂ʇoqǝɔɐʇs ☠ ~/Downloads/11219461 12:54:30 Apr23 | |
§ g++-4.8 -Wall -Werror -g -L/Users/astacy/boost/lib -I/Users/astacy/boost/include -o test test.cpp | |
test.cpp: In member function 'std::string& line_iterator::dereference() const': | |
test.cpp:33:12: error: invalid initialization of reference of type 'std::string& {aka std::basic_string<char>&}' from expression of type 'const string {aka const std::basic_string<char>}' | |
return line; | |
^ | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <fstream> | |
#include <istream> | |
#include <string> | |
#include <assert.h> | |
#include <boost/iterator/iterator_facade.hpp> | |
using namespace std; | |
class line_iterator : | |
public boost::iterator_facade< | |
line_iterator, // this class | |
istream, // the thing over which we're iterating | |
input_iterator_tag, // the iterator concept | |
string> { // the deref type | |
istream* is; | |
string line; | |
friend class boost::iterator_core_access; | |
void increment() { | |
if (is && !getline(*is, line)) | |
is = NULL; | |
} | |
bool equal(const line_iterator& other) const { | |
return this->is == other.is; | |
} | |
string& dereference() const { | |
return line; | |
} | |
public: | |
line_iterator() : is(NULL), line() {} | |
explicit line_iterator(istream* is) : is(is), line() { | |
increment(); | |
} | |
}; | |
int main(int argc, char* argv[]) { | |
ifstream f3("test/threelines.txt"); | |
ifstream f4("test/fourlines.txt"); | |
assert(distance(line_iterator(&f3), line_iterator()) == 3); | |
assert(distance(line_iterator(&f4), line_iterator()) == 4); | |
return 0; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment