I am tring to write a function to print generic map. this is what I have so far:
template<typename map_key, typename map_val>
void log(DEBUG_LEVEL level, std::map<map_key, map_val> _map) {
if (level >= d_level) {
for (std::map<map_key, map_val>::iterator it = _map.begin();
it != _map.end(); ++it)
std::cout << it->first << " => " << it->second << '\n';
}
}
it doesn't compile.
error: expected ';' before 'it'
error: 'it' was not declared in this scope
- why does this isn't compiling ?
- is there a better way to write this ? I found a one liner to print a vector here (the second answer)and I wondered if there is the same for a map ?
update: I fix the (1) but still waiting for an answer to (2)
I liked Galik answer but when I tried to add it as a function I got an error: error:'std::ostream& Logger::operator<<(std::ostream&, const std::pair<const _Key, _Tp>&)' must take exactly one argument
here is my Logger class:
extern DEBUG_LEVEL d_level;
class Logger {
public:
Logger(const char * app_name);
Logger(DEBUG_LEVEL level, char * app_name);
void log(DEBUG_LEVEL level, const char* str, ...);
template<typename vector_type>
void log(DEBUG_LEVEL level, const std::vector<vector_type>& _vec,
const std::string seperator = ", ") {
if (level >= d_level) {
std::cout << get_prefix_msg() << " ";
change_color(level);
std::cout << "[";
std::copy(_vec.begin(), _vec.end(),
std::ostream_iterator<vector_type>(std::cout,
seperator.c_str()));
std::cout << "]\n";
printf(ANSI_COLOR_RESET);
}
}
template<typename map_key, typename map_val>
void log(DEBUG_LEVEL level, const std::map<map_key, map_val>& _map,
const std::string seperator = ", ") {
if (level >= d_level) {
std::cout << get_prefix_msg() << " \n";
change_color(level);
std::cout << "[";
for (typename std::map<map_key, map_val>::const_iterator it =
_map.begin(); it != _map.end(); ++it)
std::cout << it->first << " => " << it->second << seperator;
std::cout << "]\n";
printf(ANSI_COLOR_RESET);
}
}
/**
* will log but without the application _app_name and without the debug level (but will have the right color)
*/
void strip_log(DEBUG_LEVEL level, const char* str, ...);
void change_verbosity(DEBUG_LEVEL level);
static int msg_id;
private:
const char * _app_name;
void change_color(DEBUG_LEVEL level, bool is_strip = false);
int get_next_msg_id();
std::string get_prefix_msg();
static DEBUG_LEVEL d_level;
};