Namespaces and Organization
Avoiding Name Conflicts
Namespaces allow different parts of a program to reuse the same short name safely.
Avoiding Name Conflicts
avoiding_name_conflicts.cpp
#include <iostream>
#include <string>
namespace text_view {
std::string format(int value) {
return "text:" + std::to_string(value);
}
}
namespace math_view {
std::string format(int value) {
return "double:" + std::to_string(value * 2);
}
}
int main() {
int value = ;
std::string text = text_view::format(value);
std::string math = math_view::format(value);
std::cout << text << std::endl;
std::cout << math << std::endl;
return 0;
}
#include <iostream>
#include <string>
namespace text_view {
std::string format(int value) {
return "text:" + std::to_string(value);
}
}
namespace math_view {
std::string format(int value) {
return "double:" + std::to_string(value * 2);
}
}
int main() {
int value = ;
std::string text = text_view::format(value);
std::string math = math_view::format(value);
std::cout << text << std::endl;
std::cout << math << std::endl;
return 0;
}
#include <iostream>
#include <string>
namespace text_view {
std::string format(int value) {
return "text:" + std::to_string(value);
}
}
namespace math_view {
std::string format(int value) {
return "double:" + std::to_string(value * 2);
}
}
int main() {
int value = ;
std::string text = text_view::format(value);
std::string math = math_view::format(value);
std::cout << text << std::endl;
std::cout << math << std::endl;
return 0;
}
name conflict
Two namespaces can each contain a function with the same name, and qualified names choose between them.