我知道关键字在封装方面的一般用例,friend
但有几次,我需要friend
关键字只是为了“完成工作”。这些用例并不让我高兴,所以我想知道是否有其他选择。这是第一个最小的示例:
struct Foo{
enum class Bar{
a=1,b=2,c=4
};
// need to tell the compiler of operator| before it gets used
// but it can't be a member function of Foo: so add friend keyword
friend Bar operator|(const Bar& b1, const Bar& b2);
// constructor needs a default value using
// operator| for Bars
Foo( Bar b = Bar::a | Bar::b );
};
// definition of operator|, etc.
在构造函数声明中给出默认值之前,编译器有什么方法可以在接口内部查看嵌套类的声明?operator|
Foo
我有时也会发现自己friend
在定义模板中嵌套类的对称操作时使用了关键字。例如:
template<typename T>
struct A{
struct B{
friend bool operator==(const B& x, const B& y) { return true; }
};
};
从封装的角度来看,operator==
它不需要友谊。但由于operator==
实际上不是模板化函数,并且编译器无法推断模板中嵌套类的类型,这似乎是operator==
作为自由函数保留的唯一合理“技巧”。
正如我所说,这些选择确实有效,但我想知道是否有更好的选择/实践。