我想详细解释一下这个问题。在许多具有强类型系统的语言(如 Felix、Ocaml、Haskell)中,您可以通过组合类型构造函数来定义多态列表。这是 Felix 的定义:
typedef list[T] = 1 + T * list[T];
typedef list[T] = (1 + T * self) as self;
在 Ocaml 中:
type 'a list = Empty | Cons ('a, 'a list)
在 C 中,这是递归的,但既不是多态的也不是组合的:
struct int_list { int elt; struct int_list *next; };
在 C++ 中,如果 C++ 支持类型递归,它会像这样完成:
struct unit {};
template<typename T>
using list<T> = variant< unit, tuple<T, list<T>> >;
为元组(又名对)和变体(但不是 Boost 中使用的损坏的那个)给出了合适的定义。或者:
using list<T> = variant< unit, tuple<T, &list<T>> >;
鉴于变体的定义略有不同,可能是可以接受的。甚至不可能在 C++ < C++11 中编写它,因为没有模板 typedef,就无法获得多态性,并且如果没有 typedef 的合理语法,就无法在范围内获取目标类型。上面的 using 语法解决了这两个问题,但这并不意味着允许递归。
请特别注意,允许递归对 ABI 有重大影响,即名称修改(除非名称修改方案允许表示固定点,否则无法完成)。
我的问题:需要在 C++11 中工作吗? [假设扩展不会导致无限大的结构]
编辑:为了清楚起见,要求是针对一般结构类型。模板恰好提供了这一点,例如
pair<int, double>
pair<int, pair <long, double> >
是匿名(结构上)类型的,并且 pair 显然是多态的。然而,C++ < C++11 中的递归无法声明,即使使用指针也是如此。在 C++11 中,您可以声明递归,尽管使用模板 typedef(使用新的 using 语法,= 符号的 LHS 表达式在 RHS 的范围内)。
具有多态性和递归的结构(匿名)类型是类型系统的最低要求。
任何现代类型系统都必须支持多项式类型仿函数,否则类型系统太笨拙而无法进行任何类型的高级编程。为此所需的组合器通常由类型理论家声明,例如:
1 | * | + | fix
其中 1 是单元类型,* 是元组形成,+ 是变体形成,fix 是递归。这个想法很简单:
如果 t 是一个类型并且 u 是一个类型那么 t + u 和 t * u 也是类型
在 C++ 中,struct unit{} 是 1,tuple 是 *,variant 是 +,fixpoints 可以通过 using = 语法获得。这不是完全匿名的类型,因为固定点需要模板 typedef。
编辑:只是 C 中多态类型构造函数的一个例子:
T* // pointer formation
T (*)(U) // one argument function type
T[2] // array
不幸的是,在 C 中,函数值不是组合的,指针的形成受左值约束,类型组合的语法规则本身不是组合的,但在这里我们可以说:
if T is a type T* is a type
if T and U are types, T (*)(U) is a type
if T is a type T[2] is a type
因此可以递归地应用这些类型构造函数(组合器)来获取新类型,而无需创建新的中间类型。在 C++ 中,我们可以轻松解决语法问题:
template<typename T> using ptr<T> = T*;
template<typename T, typename U> using fun<T,U> = T (*)(U);
template<typename T> using arr2<T> = T[2];
所以现在你可以写:
arr2<fun<double, ptr<int>>>
语法是组合的,输入也是如此。
最佳答案
不,那是不可能的。甚至禁止通过别名模板进行间接递归。
C++11, 4.5.7/3:
The type-id in an alias template declaration shall not refer to the alias template being declared. The type produced by an alias template specialization shall not directly or indirectly make use of that specialization. [ Example:
template <class T> struct A; template <class T> using B = typename A<T>::U; template <class T> struct A { typedef B<T> U; }; B<short> b; // error: instantiation of B<short> uses own type via A<short>::U
— end example ]
关于c++ - C++11 是否支持模板中的类型递归?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10321856/