Search code examples
c++namespacestypedefforward-declaration

Substitute the forward declared struct with lately defined struct


I'm trying to substitute the forward declared struct B with lately defined struct A. Here is a code sample:

#include <iostream>
using namespace std;

namespace n1 {
struct B;

namespace n3 {
    void func(B& b) {
        cout << "b\n";
    }
}

}

namespace n2 {
struct A{};
}

namespace n1 {
using B = n2::A;
}

int main() {
    n1::B b;
    n1::n3::func(b);
    return 0;
}

and got the following error:

conflicting declaration ‘using B = struct n2::A’
 using B = n2::A;
                ^
prog.cpp:5:8: note: previous declaration as ‘struct n1::B’
 struct B;

Is this trick possible somehow if it's even legal? Am I missing something?


Solution

  • Your using directive is creating alias to n2::A with name n1::B that is already taken by structure declaration struct B; inside namespace n1 (it is not another declaration of struct B, it is name aliasing). What you probably try to achieve is to provide a definition of your n1::B structure that might be done like this:

    namespace n1
    {
    struct B {
        // definition here, you might use your struct A if you need
    };
    }
    

    namespace docs