美文网首页
《More Effective C++》技术篇——限制某个cla

《More Effective C++》技术篇——限制某个cla

作者: 拉普拉斯妖kk | 来源:发表于2021-10-24 16:10 被阅读0次
  • 如下例,只要继承Counted template就可以限制class所能产生的对象数量,超过了设置的maxObjects就会抛出异常。
#include <stdlib.h>
#include <iostream>

template<class BeingCounted>
class Counted {
public:
    class TooManyObjects{}; //这是可能被抛出的exceptions。
    static int objectCount() { return numObjects; }

protected:
    Counted();
    Counted(const Counted& rhs);
    ~Counted() { --numObjects; }

private:
    static int numObjects;
    static const size_t maxObjects;

    void init(); //用以避免ctor码重复出现。
};

template<class BeingCounted>
Counted<BeingCounted>::Counted()
{ init(); }

template<class BeingCounted>
Counted<BeingCounted>::Counted(const Counted<BeingCounted>& rhs)
{ init(); }

template<class BeingCounted>
void Counted<BeingCounted>::init()
{
    if (numObjects >= maxObjects)
    {
        throw TooManyObjects();
    }

    ++numObjects;
}

template<class BeingCounted>
int Counted<BeingCounted>::numObjects = 0;

class Printer: private Counted<Printer> {
public:
    // pseudo-constructors
    static Printer* makePrinter() { return new Printer(); }
    static Printer* makePrinter(const Printer& rhs) { return new Printer(rhs); }
    ~Printer() {}
    
    using Counted<Printer>::objectCount;
    using Counted<Printer>::TooManyObjects;

private:
    Printer() {}
    Printer(const Printer& rhs) {}
};

template<class Printer>
const size_t Counted<Printer>::maxObjects = 5;

int main()
{
    auto p1 = Printer::makePrinter();
    auto p2 = Printer::makePrinter();
    auto p3 = Printer::makePrinter();
    std::cout << "now Printer num = " << p1->objectCount() << std::endl;
    auto p4 = Printer::makePrinter(*p1);
    auto p5 = Printer::makePrinter(*p2);
    std::cout << "now Printer num = " << p1->objectCount() << std::endl;
    //auto p6 = Printer::makePrinter(*p3); //抛出TooManyObjects的异常。
}

相关文章

网友评论

      本文标题:《More Effective C++》技术篇——限制某个cla

      本文链接:https://www.haomeiwen.com/subject/ntmraltx.html