[英]How to count the number of CRTP subclasses of a template class?
有没有人知道使用CRTP计算对象子类数的方法?
假设我们有类似于以下设置:
template <typename T>
class Object
{
....
};
const unsigned int ObjectSubClassCount = ...;
class Subobject : public Object<SubObject>
{
....
};
class Second : public Object<Second>
{
....
};
等等,使用TMP,我们可能有一个表示子类总数的常量( ObjectSubClassCount
)?
有谁知道这样做的方法?
编辑:我想稍后将结果用作模板参数,所以我需要用TMP来完成...
如果没有要求将结果用作模板参数,我会尝试这样做:
// Class which increments a given counter at instanciation
struct Increment {
Increment(std::size_t& counter)
{
counter++;
}
};
// This is your template base
template <typename T>
class Object
{
private:
// For every instanciation of the template (which is done for a subclass)
// the class counter should get incremented
static Increment incrementCounter;
};
// This is the global object counter
static std::size_t classCounter;
// Static Member Variable
template<typename T>
Object<T>::incrementCounter(classCounter);
没试过但是应该这样做。 要使结果再次作为模板参数(MPL),我没有足够的MPL经验,但我怀疑这是可能的。
好的,所以我遇到了......有些可以接受的答案。 我认为,如果子类完全不了解彼此(我的意思是,我们正在谈论一些函数式编程......),这将无法解决。
这是一个解决方案。 这绝对不是我想要的解决方案; 然而,这是一个开始。 我强迫所有对象使用CRTP形式,但是使用更多链接列表格式。 这样,我们的子类必须从一个对象<>派生自:
答:本身和B:最近定义的子类
这是我的代码(我使用<type_traits>
的模板一次,只是一个注释)
template <typename T> //SFINAE check for the existance of subclasscount static member
struct has_subclasscount
{
template <typename U>
static typename std::enable_if<sizeof(U::subclasscount) != 0, int>::type test(int);
template <typename U>
static char test(...);
static const bool result = (sizeof(test<T>(0)) == sizeof(int))?(true):(false);
};
template <bool res, typename T>
struct return_subclasscount //the value to return is 0 if false
{
static const int result = 0;
};
template <typename T>
struct return_subclasscount<true, T> //returns subclasscount only if the first parameter is true
{
static const int result = T::subclasscount;
};
template <typename T> //combines return_subclasscount and has_subclasscount
struct get_subclasscount
{
static const int result = return_subclasscount<has_subclasscount<T>::result, T>::result;
};
template <typename This, typename Prev>
class Object
{
public:
static const int subclasscount = 1 + get_subclasscount<Prev>::result; //the subclass count
};
class sub1 : public Object<sub1, int>
{
};
class sub2 : public Object<sub2, sub1>
{
};
class sub3 : public Object<sub3, sub2>
{
};
最后3个空类是我们计算的子类。 这是我们的头文件。 在我们的主.cpp文件中,我们有:
int main() {
std::cout << sub3::subclasscount;
char c;
std::cin >> c;
}
运行它,我们得到一个简单的输出:
3
这证实它有效。 现在,这个解决方案的一些缺点是:
但是,好处包括我们不需要维护任何先前定义的子类。 但是,我认为这个答案更像是一个“起点”,而不是“最终解决方案”; 也许可以扩展的东西?
(另外,这很容易被滥用来构成一种树形结构,其中subclasscount
实际上代表树中任何给定节点的深度)
任何人有任何想法吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.