【问题标题】:C++ template metaprogramming: constexpr functionC++ 模板元编程:constexpr 函数
【发布时间】:2015-01-01 04:35:17
【问题描述】:

我在看 Bjarne Stroustrup 的演讲“The Essential C++”。

在问答环节,关于如何管理繁重的模板编程代码,他提到:“通过constack perfunction,您可以基本上消除所有通过编写普通代码生成值的模板元编程”。 p>

constack perfunction 只是一个疯狂的猜测。

请问该技术的正确术语是什么?以便我可以做一些后续阅读。

更新:只需将标题修改为“constexpr function”即可。

【问题讨论】:

  • constexpr 函数?
  • 请看你能不能得到他的演讲稿。你连续添加了太多同一个演讲的问题!!男人。
  • 可能是 constexpr 函数,我在answer here 中举了一个例子,说明如何用 constexpr 函数替换模板元编程。我的示例来自Want speed? Use constexpr meta-programming!,这是一篇关于该主题的好文章。
  • constack perfunction:(v)每个函数(perfunction)的倒置堆栈(constack)。另外,不是实际的单词。
  • @ShafikYaghmour 谢谢你!

标签: c++ templates metaprogramming


【解决方案1】:

constexpr 函数,在 C++11 中添加,可以在编译时进行评估,并在模板元编程中用作模板参数。在 C++11 中,它们非常有限,并且(几乎)只能由单个 return 表达式组成。 C++14 减少了它们的限制。

例如这是可能的:

constexpr std::size_t twice(std::size_t sz) {
    return 2 * sz;
}

std::array<int, twice(5)> array;

而在 C++11 之前,需要模板“hacks”,例如:

template<std::size_t sz>
class twice {
public:
    static const std::size_t value = 2 * sz;
}

std::array<int, twice<5>::value> array;

例如,它可用于在编译时以干净的方式生成值(如数学常数、三角查找表等)。

【讨论】:

    猜你喜欢
    • 2012-03-18
    • 2018-07-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-11
    • 2012-08-27
    • 2012-02-21
    相关资源
    最近更新 更多