template function

Hello everyone, sorry for the bad English. I have a problem with the template functions.
I have these two template functions
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
namespace database {

template <class KEY, class TYPE> 
	void write (std :: ofstream& stream, std :: map <KEY, TYPE>& __map) {
		unsigned elementNumber = __map.size();
		stream.write(reinterpret_cast <const char*> (&elementNumber), sizeof (unsigned));

		typename std :: map <KEY, TYPE> :: const_iterator it;
		for (it = __map.begin(); it != it.end(); it++) {
			stream << it -> first;
			stream << it -> second;
		}
	}

	template <class KEY, class TYPE> 
	void read (std :: ifstream& stream, std :: map <KEY, TYPE>& __map) {
		unsigned elementNumber;
		stream.read(reinterpret_cast <char*> (&elementNumber), sizeof(unsigned));
		
		KEY key;
		TYPE type;
		for (unsigned i = 0; i < elementNumber; i++) {
			stream >> key;
			stream >> type;
			__map[key] = type;
		}
	}

}


when i try to call them in main

1
2
3
std :: map <std :: string, std :: string> __map;
...
database:: write <std :: string, std :: string> (fileStream, __map);


or

 
database:: read <std :: string, std :: string> (fileStream, __map);


i get those errors form g++

1
2
3
4
5
6
test.cpp:43:113: error: no matching function for call to ‘write(std::fstream&, std::map<std::basic_string<char>, std::basic_string<char> >&)’
test.cpp:43:113: note: candidate is:
database/fileManager.hpp:72:7: note: template<class KEY, class TYPE> void database::write(std::ofstream&, std::map<KEY, TYPE>&)
test.cpp:48:110: error: no matching function for call to ‘read(std::fstream&, std::map<std::basic_string<char>, std::basic_string<char> >&)’
test.cpp:48:110: note: candidate is:
database/fileManager.hpp:84:7: note: template<class KEY, class TYPE> void database::read(std::ifstream&, std::map<KEY, TYPE>&)


can anyone help me? I do not know how to solve ...
Thanks!

I think you can just:
database:: read(fileStream, __map);
Seems to work ok on gcc 4.0.1.

You do have an error though, this:
 
for (it = __map.begin(); it != it.end(); it++) {

should be this:
 
for (it = __map.begin(); it != __map.end(); it++) {

Last edited on
Quick question: how did you define fileStream?

I made the first arguments of the std::stringstream type and this worked for me, or I could just call database::write with std::cout.

It fails with g++ (Debian 4.4.5-8) 4.4.5
1
2
3
4
5
6
#include <fstream>
void foo( std::ofstream&) ;
int main(){
   std::fstream file;
   foo(file);
}

error: invalid initialization of reference of type ‘std::ofstream&’ from expression of type ‘std::fstream’
error: in passing argument 1 of ‘void foo(std::ofstream&)’


IIRC fstream does derive from ofstream and ifstream, so I guess it is a bug in the compiler.
fstream isn't derived from ofstream
Topic archived. No new replies allowed.