问题描述
示例:
template<class T>
class Base {
public:
Base();
friend class T;
};
现在这不行了...有办法吗?
Now this doesn't work... Is there a way of doing this?
我实际上是想像这样做一个一般的类封装:
I'm actually trying to make a general class sealer like this:
class ClassSealer {
private:
friend class Sealed;
ClassSealer() {}
};
class Sealed : private virtual ClassSealer
{
// ...
};
class FailsToDerive : public Sealed
{
// Cannot be instantiated
};
我在这个网站上找到这个例子,但我找不到... href =http://stackoverflow.com/questions/656224/when-should-i-use-c-private-inheritance/656523#656523>这里)
I found this example on this site somewhere but I can't find it... (here)
我知道有这样做,但刚才我很好奇
I know there are other ways of doing this but just now I'm curious if you actually can do something like this.
推荐答案
它在标准中明确禁止,即使有些版本的VisualStudio允许
It is explicitly disallowed in the standard, even if some versions of VisualStudio do allow it.
C ++标准7.1.5.3详细说明的类型说明符,第2段
C++ Standard 7.1.5.3 Elaborated type specifiers, paragraph 2
我认为上面的代码是一个密封(不允许扩展)类的模式。还有另一个解决方案,这并不真正阻止扩展,但将标记从类无名地扩展。如中所示:
I recognize the code above as a pattern to seal (disallow the extension of) a class. There is another solution, that does not really block the extension but that will flag unadvertidly extending from the class. As seen in ADOBE Source Library:
namespace adobe { namespace implementation {
template <class T>
class final
{
protected:
final() {}
};
}}
#define ADOBE_FINAL( X ) private virtual adobe::implementation::final<T>
与用法:
class Sealed : ADOBE_FINAL( Sealed )
{//...
};
虽然它允许扩展,如果你真的强迫它:
While it allows extension if you really force it:
class SealBreaker : public Sealed, ADOBE_FINAL( Sealed )
{
public:
SealBreaker() : adobe::implementation::final<Sealed>(), Sealed() {}
};
这将限制用户错误地执行此操作。
It will restrict users from mistakenly do it.
编辑:
即将到来的C ++ 11标准允许您使用稍微不同的语法来处理类型参数:
The upcoming C++11 standard does allow you to befriend a type argument with a slightly different syntax:
template <typename T>
class A {
// friend class T; // still incorrect: elaborate type specifier
friend T; // correct: simple specifier, note lack of "class"
};
这篇关于使模板参数成为朋友?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!