c++ - Unnamed namespace cannot be placed in .h
phpcn_u1582
phpcn_u1582 2017-05-16 13:21:09
0
1
869

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.

phpcn_u1582
phpcn_u1582

reply all(1)
PHPzhong

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….

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!