什么样的C++模板编程才叫"meta programming"?

What kind of C++ template programming can be called "meta programming"?

  1. 用什么样的模板技术,才能称得上"meta programming"?
  2. 是否有关于什么是元编程和什么不是元编程的良好定义?
  3. 我们的 C++11 STL 是否包含大量元编程?
  4. 是"type_traits"元编程吗?

非常感谢。

"Metaprogramming" 用于非正式演讲,指代各种编程技术:

  • 关于类型的信息,即 "type traits"。这是最直接的元类型,因为 "meta" 这里的意思是 "about something"

  • (Ab)使用 C 预处理器或模板。您并不是真正在编程 "in" C++,而是一种子语言。 IOCCC 有很多人使用 C 预处理器执行各种完整程序的示例,例如河内塔和计算素数。模板元程序的 "classic" 示例正在计算斐波那契数列。换句话说,您将 "outside" C++ 的正常范围来创建程序,这使得这种用法类似于 metagaming

  • Quines,创建程序,创建程序,自托管编译器等。这里"meta"表示"self-referential",就像一个分形

标准库是否包含"metaprogramming"是实现定义的。有些实现会因此而疯狂,有些则不会。

也没有很好的定义,"meta"这个词有点模糊。

Q1.使用什么样的模板技术,才能称得上"meta programming"?

模板元编程是指使用模板和编译器来执行编程的一些关键元素:循环、if-else 分支、C/C++ 分支、递归等开关

第一个这样的元程序用于生成前几个质数作为编译器错误消息。参见 http://www.erwin-unruh.de/primorig.html

Q2.是否有关于什么是元编程和什么不是元编程的良好定义?

可以在 Wikipedia 找到一个很好的定义。

Template metaprogramming (TMP) is a metaprogramming technique in which templates are used by a compiler to generate temporary source code, which is merged by the compiler with the rest of the source code and then compiled. The output of these templates include compile-time constants, data structures, and complete functions. The use of templates can be thought of as compile-time execution. The technique is used by a number of languages, the best-known being C++, but also Curl, D, and XL.

Q3.我们的C++11 STL是否包含大量元编程?

很有可能,但这是一个猜测。我还没有深入研究标准库的任何实现。

Q4.是"type_traits"元编程吗?

再一次,我没有深入研究它,但我想 "type_traits" 的大部分功能都是使用元编程技术实现的。