CRTP - 计算单个类和总计数 [英] CRTP - Counting Individual Classes and Total Count
问题描述
我最近学到了CRTP,并且已经练习了一些更好的文档代码示例,以便更好地理解它。目前的代码块我有能够计数不同派生类的实例,但如果我想找到所有实例的总和,而不管类?这里是我有的代码:
I've recently learned about CRTP and have been practicing some of the better documented code examples out there to understand it better. Currently the block of code I have is able to count the instances of different derived classes but what if I want to find the total of all instances regardless of class? Here is the code I have:
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;
}
当前注释掉的最后一行是我想要的方式调用查看当前有多少总对象。我知道我可以通过创建一个全局计数器并在类中创建一个新的函数来返回这个全局计数,但我想要能够像这样调用,而不定义一个模板参数,以另一种方式找到总计。我必须做一个Adapter类型的接口,或者有更容易的方法来实现这个?
The last line that is currently commented out is the way I want to be able to call to see how many total objects there currently are. I know I can find the total out another way by creating a global counter and creating a new function within the class to return that global count but I want to be able to call it like this, without defining a templated argument. Do I have to make an Adapter sort of interface or is there an easier way of implementing this?
谢谢。
推荐答案
解决方案1
设置 countable
非模板类的派生类,例如 countable_base
,并将所有计数代码移动到基类。
Make countable
a derived class of a non-template class, such as countable_base
, and move all the counting code to the base class.
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
使可计数
为一般课程。
class countable {
static unsigned count_;
public:
countable() { ++count_; }
countable(countable const&) { ++count_; }
~countable() { --count_; }
static unsigned n_alive() { return count_; }
};
unsigned countable::count_ = 0;
这篇关于CRTP - 计算单个类和总计数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!