我在 C++ 中使用模板元编程通过使用类型列表生成类的层次结构,如下所示:
//! Basic typelist class
template<class H, class T>
class Typelist
{
public:
typedef H Head;
typedef T Tail;
};
//! Terminating type
class NullType {};
//! Forward declaration
template<class Types>
class Recur;
//! Specialisation to terminate the recursion
template<>
class Recur<NullType>
{
};
//! General recursive class
template<class Types>
class Recur: public Recur<typename Types::Tail>
{
};
// Dummy classes
class Type1{};
class Type2{};
class Type3{};
int main()
{
// Defines the typelist
typedef Typelist<Type1,Typelist<Type2,Typelist<Type3,NullType>>> Types;
// Instantiate the recursion
Recur<Types> recur;
return 1;
}
这会产生一个像这样的类层次结构:
Recur<Typelist<Type2,Typelist<Type3,NullType>>>
源自:
Recur<Typelist<Type3,NullType>>
源自:
Recur<NullType> (base class)
问题:对于使用这种递归技术的类派生深度,Visual Studio 2010 编译器是否有任何限制?换句话说,如果我的类型列表包含 N 个类型,即使 N 等于 100,000,上面的代码也会编译和构造 N 个类吗?
最佳答案
Standard 的附件 B仅指定最低级别的直接和间接基类和嵌套模板实例化,具体编译器是否超出此范围是实现质量问题。请查阅您的特定编译器自己的文档以获取精确值。以下是标准要求的最低数量。
附件 B(资料性) 实现数量[限制]
1 Because computers are finite, C++ implementations are inevitably limited in the size of the programs they can successfully process. Every implementation shall document those limitations where known. This documentation may cite fixed limits where they exist, say how to compute variable limits as a function of available resources, or say that fixed limits do not exist or are unknown.
2 The limits may constrain quantities that include those described below or others. The bracketed number following each quantity is recommended as the minimum for that quantity. However, these quantities are only guidelines and do not determine compliance.
— Direct and indirect base classes [16 384].
— Direct base classes for a single class [1 024].
— Recursively nested template instantiations, including substitution during template argument deduction (14.8.2) [1 024].
关于c++ - 元编程继承限制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14603752/