Unnamed namespace cannot be placed in .h. Can you give an example why it is not allowed?
I thought about it but couldn’t find an example.
PHPz2017-05-16 13:23:09
The key depends on how to use it and what to put in the unnamed namespace. For example, if you put variables, there will be problems.
//one.h
#include <iostream>
#include <typeinfo>
namespace {
class TestClass {
};
int i;
}
const std::type_info& one_get_TestClass_Info();
const std::type_info& two_get_TestClass_Info();
//one.cpp
#include "one.h"
const std::type_info& one_get_TestClass_Info()
{
i = 10;
std::cout << "val: " << i << " addr: " << &i << std::endl;
return typeid(TestClass);
}
//two.cpp
#include "one.h"
#include <iostream>
#include <typeinfo>
using namespace std;
const std::type_info& two_get_TestClass_Info()
{
std::cout << "val: " << i << " addr: " << &i << std::endl;
return typeid(TestClass);
}
//main.cpp
#include "one.h"
using namespace std;
int main()
{
const std::type_info& t1 = one_get_TestClass_Info();
const std::type_info& t2 = two_get_TestClass_Info();
std::cout << "one has type: " << t1.name() << '\n'
<< "two has type: " << t2.name() << '\n';
if (t1 == t2) {
cout << "same type";
}
return 0;
}
The output is:
val: 10 addr: 0x602200
val: 0 addr: 0x602208
one has type: N12_GLOBAL__N_19TestClassE
two has type: N12_GLOBAL__N_19TestClassE
For a little more details, see here: https://zsounder.github.io/20….