且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

允许模拟类从最终类继承

更新时间:2023-11-19 23:04:28

但是,如何使它成为最终的,同时允许一个类继承它呢?

But, how to make it final, yet allow one class to inherit from it?

这不可能.

我们主要需要从真实类派生出一个模拟类(有或没有后期绑定,因此虚拟并不重要).

We mostly need to derive a mock class from real class (with or without late-binding, hence virtual isn't important).

如果类是最终的,您不需要从它派生.如果您确实需要从中派生,它不是最终的.选择一个.

If the class is final, you do not need to derive from it. If you do need to derive from it, it is not final. Pick one.

编辑:您可以向您的类添加限制,但这些限制会影响界面:

Edit: You can add restrictions to your class, but those come at their own cost to the interface:

class Generator // not final
{
    Generator(); // the only accessible constructor is private

    // whitelist who has access to this constructor
    friend class MockGenerator;
public:
    // no public constructors here except for copy & move

    Generator(Generator&);
    Generator(Generator&&);
    ...

    // provide controlled access to the private constructor
    static Generator make_generator() { return Generator(); }

    // rest of API here
};

这是一个允许它的工厂和 MockGenerator 特化调用它的构造函数的类.但是,这是以阻止琐碎构造为代价的.

This is a class that allows it's factory and MockGenerator specializations to call it's constructor. This comes at the price of blocking trivial construction though.

旧代码(不再可编译):

Old code (no longer compilable):

Generator instance;

新代码(由私有构造函数强制执行):

New code (enforced by the private constructor):

auto instance = Generator::make_generator();