#include <iostream>
namespace outside {
struct A {
int outer = 42;
friend void print(A const& a, std::ostream& os)
{ os << "outside::A " << a.outer << '\n'; }
};
namespace inside {
struct A : outside::A {
int inner = 24;
void print(std::ostream& os) { } // Added for extra difficulty
friend void print(A const& a, std::ostream& os) {
// outside::A::print(a, os); // <- does not compile
os << " inside::A " << a.inner << '\n';
}
};
} // inside
} // outside
int main(int argc, char *argv[]) {
outside::A a_outside;
outside::inside::A a_inside;
print(a_outside, std::cout);
print(a_inside, std::cout);
}
有没有办法限定打印功能,以便打印基本成员和派生成员?我可以将两个友元函数移动到它们最近的封闭命名空间:
#include <iostream>
namespace outside {
struct A { int outer = 42; };
void print(A const& a, std::ostream& os)
{ os << "outside::A " << a.outer << '\n'; }
namespace inside {
struct A : outside::A {
void print(std::ostream& os) { } // Added for extra difficulty
int inner = 24;
};
void print(A const& a, std::ostream& os) {
outside::print(a, os); // <- works
os << " inside::A " << a.inner << '\n';
}
} // inside
} // outside
int main(int argc, char *argv[]) {
outside::A a_outside;
outside::inside::A a_inside;
print(a_outside, std::cout);
print(a_inside, std::cout);
}
这有效,结果如下:
outside::A 42
outside::A 42
inside::A 24
可以通过朋友功能实现相同的功能吗?也许使用using
?
编辑:inside::A::print(std::ostream&)
击败下面的静态演员建议,https ://stackoverflow.com/a/22585103/710408 。还有其他选择吗?