CRTP - 计算单个类和总计数

时间:2014-07-31 18:35:39

标签: c++ crtp

我最近了解了CRTP,并且已经练习了一些更好的文档代码示例,以便更好地理解它。目前我所拥有的代码块能够计算不同派生类的实例,但是如果我想查找所有实例的总数而不管类是什么?这是我的代码:

template <typename CountedType>
class countable {
    static unsigned count_;
public:
    countable() { ++count_; }
    countable(countable const&) { ++count_; }
    ~countable() { --count_; }

    static unsigned n_alive() { return count_; }

};
template <typename CountedType>
unsigned countable<CountedType>::count_ = 0;

template <typename CharT>
class BasicMyString : public basic_string < CharT >, public countable<BasicMyString<CharT>> { };


typedef BasicMyString<char> MyString;
typedef BasicMyString<wchar_t> WMyString;

template <typename T>
class MyVector : public vector<T>, public countable<MyVector<T>> {};

int main() {
    MyString s1, s2;
    WMyString wms;
    MyVector<double> v;

    cout << "Number of MyString: " << MyString::n_alive() << endl;
    cout << "Number of WMyString: " << WMyString::n_alive() << endl;
    cout << "Number of MyVector: " << MyVector<double>::n_alive() << endl;
   //cout << "Total number of objects: " << countable::n_alive() << endl;
}

当前注释掉的最后一行是我希望能够调用以查看当前有多少总对象的方式。我知道我可以通过创建一个全局计数器并在类中创建一个新函数来返回全局计数,但我希望能够像这样调用它而不定义模板化参数。我是否必须使用适配器类接口或者是否有更简单的方法来实现它?

感谢。

2 个答案:

答案 0 :(得分:2)

解决方案1 ​​

使countable成为非模板类​​的派生类,例如countable_base,并将所有计数代码移动到基类。

class countable_base {
    static unsigned count_;
public:
    countable_base() { ++count_; }
    countable_base(countable_base const&) { ++count_; }
    ~countable_base() { --count_; }

    static unsigned n_alive() { return count_; }

};
unsigned countable_base::count_ = 0;

template <typename CountedType>
class countable : public countable_base {};

解决方案2

countable成为常规课程。

class countable {
    static unsigned count_;
public:
    countable() { ++count_; }
    countable(countable const&) { ++count_; }
    ~countable() { --count_; }

    static unsigned n_alive() { return count_; }

};
unsigned countable::count_ = 0;

答案 1 :(得分:1)

您可以创建一个额外的类来进行计数,这将是您当前模板countable类的基础,类似于:

class countable_total {
    static unsigned count_;
protected:
    countable_total() { ++count_; }
    countable_total(countable_total const&) { ++count_; }
    ~countable_total() { --count_; }
public:
    static unsigned n_alive() { return count_; }
};

template <typename CountedType>
class countable : public countable_total {
    static unsigned count_;
public:
    countable() { ++count_; }
    countable(countable const&) { ++count_; }
    ~countable() { --count_; }

    static unsigned n_alive() { return count_; }
};

template <typename CountedType>
unsigned countable<CountedType>::count_ = 0;

// in cpp
unsigned countable_total::count_ = 0;