Reputation: 23
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?
Upvotes: 0
Views: 43
Reputation: 217235
You cannot forward declared aliases.
a workaround, if appropriate, is to use inheritance instead of alias:
namespace n1 {
struct B;
namespace n3 {
void func(B& b) {
cout << "b\n";
}
}
}
namespace n2 {
struct A{};
}
namespace n1 {
struct B : n2::A{};
}
but
n2::A a;
n1::n3::func(a); // Fail, a is not n1::B
Upvotes: 1
Reputation: 8217
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
};
}
Upvotes: 1