简体   繁体   中英

How do I forward declare a typedef in C++?

I have two namespaces ( F and M ) where I used typedef to define something. I use the typedef in one namespace to declare a variable in the other namespace.

For example I have these files:

File M.hpp

#ifndef M_HPP
#define M_HPP

#include "F.hpp"

namespace M{
    typedef std::vector<F::myD> VectorDouble;

class M{
    private:
        VectorDouble Diction;
};
}

#endif  // M_HPP

File F.hpp

#ifndef F_HPP
#define F_HPP

#include "M.hpp"

namespace F{
    typedef double myD;

class MyF{
    private:
        M::VectorDouble myVar;
};
}

#endif  // F_HPP

It is immediately clear that these two header files create a circular dependance so forward declaration may be necessary, but how to do that with namespaces and typedefs?

File namespace.cpp to drive the code:

#include <iostream>
#include <vector>

#include "M.hpp"
#include "F.hpp"

int main(){
    std::cout << "Learning how to access stuff in a namespace." << std::endl;

    F::MyF myFInstance;
    M::M myMInstance;

    return 0;
}

When I try to compile, I get an error that my M is an undeclared identifier (see exact error message below). I don't understand why M isn't seen as a namespace .

$ clang++ -std=c++11 -stdlib=libc++ namespace.cpp -o namespace
In file included from namespace.cpp:5:
In file included from ./M.hpp:5:
./F.hpp:12:9: error: use of undeclared identifier 'M'
        M::VectorDouble myVar;
        ^
1 error generated.

How can I access a typedef from another namespace? Is this a forward declaration issue?

Your issue is that you have created circular includes .

By your own coding, your file F.hpp can't be compiled without first including M.hpp .

And M.hpp can't be compiled without first including F.hpp .

Therefore, neither header can be compiled. See this SO post for solutions to circular dependencies.

Edit:

You can forward declare your typedef like this.

File F_fwd.hpp

#ifndef F_FWD_HPP
#define F_FWD_HPP

namespace F{
    typedef double myD;
}

#endif // F_FWD_HPP

您的两个标头彼此包含在一起,这将导致循环引用,并且使用标头域,一个文件可以完全排除在其他标头之一中。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM