模板类的编译时计数器

时间:2011-04-11 15:47:57

标签: c++ templates c++11

想象一下,你有很多具有许多不同模板参数的类。每个类都有一个方法static void f()。您希望在列表L中收集所有这些函数指针。

运行时解决方案很简单:

typedef void (*p)();
std::vector<p> L;
int reg (p x) { static int i = 0; L.push_back(x); return i++; } // also returns an unique id

template <typename T> struct regt { static int id; };
template <typename T> int regt<T>::id = reg (T::f);

template < typename ... T > struct class1 : regt< class1<T...> > { static void f(); };
template < typename ... T > struct class2 : regt< class2<T...> > { static void f(); };
// etc.

编译器在编译时知道所有实例化类的所有f()。因此,理论上应该可以生成这样的列表(一个const std::array<p, S> L,其中包含S}作为编译时常量列表。但是怎么样? (C ++ 0x解决方案也很受欢迎)。


为什么我需要这个?

在只有256 kB的架构上(对于代码和数据),我需要为类的传入ID生成对象。上面的现有序列化框架或运行时解决方案不必要地大。没有模板,编译时解决方案很容易,但我想保留模板提供的所有优势。

2 个答案:

答案 0 :(得分:4)

手动

你能做的最简单的事情就是手动滚动代码,我认为从模板中可以利用很多东西,所以我会使用普通类,其中AB ...代表您的类型的特定实例。这允许类型的编译时初始化,代价是每当将新类型添加到系统时必须记住更新查找表:

typedef void (*function_t)();
function_t func[] = {
    &A::f,
    &B::f,
    &C::f
};

从维护的角度来看,我会建议这样做。自动化系统将使代码在将来更难理解和维护。

<强>宏

简单最自动化的,可能会产生更少的代码是宏生成系统只是使用宏。由于第一种方法将广泛使用宏,我将自动生成函数,就像您在上一个问题中所做的那样。如果您(希望)放弃了通过宏生成完整代码的路径,则可以删除该部分代码。

为了避免必须在不同的上下文中重新键入类型的名称,您可以定义一个包含任何上下文所需的所有数据的宏,然后使用其他宏来过滤每个特定的内容(以及如何使用)上下文:

// This is the actual list of all types, the id and the code that you were
// generating in the other question for the static function:
#define FOREACH_TYPE( macro ) \
    macro( A, 0, { std::cout << "A"; } ) \
    macro( B, 1, { std::cout << "B"; } ) \
    macro( C, 2, { std::cout << "C"; } )

// Now we use that recursive macro to:
// Create an enum and calculate the number of types used
#define ENUM_ITEM( type, id, code ) \
    e_##type,
enum AllTypes {
    FOREACH_TYPE( ENUM_ITEM )
    AllTypes_count
};
#undef ENUM_ITEM

// Now we can create an array of function pointers
typedef void (*function_t)();
function_t func[ AllTypes_count ];

// We can create all classes:
#define CREATE_TYPE( type, the_id, code ) \
struct type {\
   static const int id = the_id; \
   static void func() code\
};
FOREACH_TYPE( CREATE_TYPE )
#undef CREATE_TYPE

// And create a function that will 
#define REGISTER_TYPE( type, id, code ) \
    func[ i++ ] = &type::func;

void perform_registration() {
   int i = 0;
   FOREACH_TYPE( REGISTER_TYPE );
};
#undef REGISTER_TYPE

// And now we can test it
int main() {
   perform_registration();
   for ( int i = 0; i < AllTypes_count; ++i ) {
      func[ i ]();
   }
}
另一方面,这是一个维护噩梦,非常脆弱,难以调试。添加新类型是微不足道的,只需在FOREACH_TYPE宏中添加一个新行即可完成...并且一旦失败就会好运......

模板和元编程

另一方面,使用模板可以获得关闭,但无法达到类型的单点定义。您可以通过不同方式自动执行某些操作,但至少您需要自己定义类型并将它们添加到类型列表中以获得其余功能。

使用C ++ 0x代码简化实际type_list的定义,您可以先定义类型,然后创建type_list。如果你想避免使用C ++ 0x,那么看看Loki库,但是使用C ++ 0x,类型列表很简单:

template <typename ... Args> type_list {}; // generic type list
typedef type_list< A, B, C, D > types;     // our concrete list of types A, B, C and D
                                           // this is the only source of duplication:
                                           // types must be defined and added to the
                                           // type_list manually [*]

现在我们需要使用一些元编程来操作类型列表,我们可以例如计算列表中元素的数量:

template <typename List> struct size;     // declare
template <typename T, typename ... Args>  // general case (recursion)
struct size< type_list<T,Args...> > {
   static const int value = 1 + size< type_list<Args...>::value;
};
template <>                               // stop condition for the recursion
struct size< type_list<> > {
   static const int value = 0;
};

拥有类型列表的大小是我们问题的第一步,因为它允许我们定义一个函数数组:

typedef void (*function_t)();                 // signature of each function pointer
struct registry {
   static const int size = ::size< types >::value;
   static const function_t table[ size ];
};
function_t registry::table[ registry::size ]; // define the array of pointers

现在我们想要从该数组中的每个特定类型注册静态函数,为此我们创建一个辅助函数(封装为类型中的静态函数以允许部分特化)。请注意,这个具体部分设计为在初始化期间运行:它不是编译时间,但成本应该是微不足道的(我会更担心所有模板的二进制大小):

template <typename T, int N>                         // declaration
struct register_types_impl;
template <typename T, typename ... Args, int N>      // general recursion case
struct register_types_impl< type_list<T,Args...>, N> {
   static int apply() {
      registry::table[ N ] = &T::f;                  // register function pointer
      return register_types_impl< type_list<Args...>, N+1 >;
   }
};
template <int N>                                     // stop condition
struct register_types_impl< type_list<>, int N> {
   static int apply() { return N; }
};
// and a nicer interface:
int register_types() {
   register_types_impl< types, 0 >();
}

现在我们需要一个id函数将我们的类型映射到函数指针,在我们的例子中是类型列表中类型的位置

template <typename T, typename List, int N>      // same old, same old... declaration
struct id_impl;
template <typename T, typename U, typename ... Args, int N>
struct id_impl< T, type_list<U, Args...>, N > {  // general recursion
   static const int value = id_impl< T, type_list<Args...>, N+1 >;
};
template <typename T, typename ... Args, int N>  // stop condition 1: type found
struct id_impl< T, type_list<T, Args...>, N> {  
   static const int value = N;
};
template <typename T, int N>                     // stop condition 2: type not found
struct id_impl< T, type_list<>, N> {
   static const int value = -1;
}
// and a cleaner interface
template <typename T, typename List>
struct id {
   static const int value = id_impl<T, List, 0>::value;
};

现在您只需要在运行时触发注册,然后再执行任何其他代码:

int main() {
   register_types(); // this will build the lookup table
}

[*] 嗯......有点,你可以使用宏技巧来重用这些类型,因为宏的使用是有限的,它不会那么难维护/调试。

答案 1 :(得分:1)

  

编译器在编译时知道所有实例化类的所有f()

你的错误。编译器对其他编译单元中的模板实例化一无所知。现在应该很明显为什么实例化的数量不是一个可以用作模板参数的常量积分表达式(如果std::array是专用的,那该怎么办?暂停问题!)