私人朋友运算符< [英] private friend operator<<
问题描述
所以我有一个类,我想重载运算符<<
能够输出
其内部数据到输出流。我想这样做只是为了调试
的目的,从而以某种方式完全隐藏来自外界的运算符<
,
,只有在我的类的
实现所在的 *。cpp
文件内。要让我的类中的运算符<<
访问成员
变量,我必须让它成为它的朋友。然而,在类中声明
运算符<<
的朋友使得来自外部世界的任何人能够调用
operator< code>对这个类...
我知道我可以做一个常规的私人成员函数来做这个,
但我已经有一些调试宏使用运算符<
,
所以我想知道是否可能得到这个做的某种方式。
<$ class =h2_lin>解决方案
您可以将运算符<<
功能移动到辅助代理类。当代理被用作<<
的RHS时,则打印原始对象。定义从原始到代理的私有
隐式转换。现在任何人都可以访问运算符<<
,但只有该类具有构造代理的能力。
class private_printable {
int state;
struct proxy {
private_printable const& r;
};
operator proxy()const {return {* this}; }
friend std :: ostream&运算符<< (std :: ostream& s,proxy const& o)
{return s<状态}
public:
private_printable():state(5){}
void debug(){std :: cout< *这<< '\\\
'; }
};
请注意,代理不需要加入。从正常的做事的唯一的变化是代理和转换功能存在。 friend运算符<<
是通过参数依赖查找找到的,没有命名空间范围声明,即使它不需要 private_printable
参数。然后转换使它可行。不要认为更清洁的解决方案是可能的:v)。
So I have a class for which I want to overload operator<<
to be able to output
its internal data to output stream. I want to do this only for debugging
purposes and thus somehow completely hide the operator<<
from outside world,
so that it will be accessible only from within the *.cpp
file where the
implementation of my class resides. To give the operator<<
access to member
variables from my class I have to make it a friend of it. However declaring
operator<<
friend in the class enables anyone from outside world to call
operator<<
on this class ...
I know that I could make a regular private member function to do this,
but I already have some debugging macros that make use of operator<<
,
so I was wondering if it was possible to get this done somehow.
You can move the operator<<
functionality to a helper proxy class. When the proxy is used as the RHS of <<
, then the original object is printed. Define a private
implicit conversion from the original to the proxy. Now anyone has access to operator<<
, but only the class has the ability to construct the proxy.
class private_printable {
int state;
struct proxy {
private_printable const &r;
};
operator proxy () const { return { * this }; }
friend std::ostream & operator << ( std::ostream & s, proxy const & o )
{ return s << o.r.state; }
public:
private_printable() : state( 5 ) {}
void debug() { std::cout << * this << '\n'; }
};
Note that the proxy doesn't need to be friended. The only change from the normal way of doing things is that the proxy and conversion function exist. The friend operator<<
is found by argument-dependent lookup, without a namespace-scope declaration, even though it doesn't take a private_printable
argument. Then the conversion makes it viable. Don't think a cleaner solution is possible :v) .
这篇关于私人朋友运算符<的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!