C ++模板元编程:constexpr函数

时间:2015-01-01 04:35:18

标签: c++ templates metaprogramming

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

在Q& A会话中,关于如何管理繁重的模板编程代码,他提到:“通过 constack perfunction ,您可以基本上消除每个通过编写普通代码生成值的模板元编程”。

constack perfunction 只是声音的疯狂猜测。

请问这项技术的正确用语是什么?所以我可以做一些跟进阅读。

更新:只需将标题修改为“constexpr功能”。

1 个答案:

答案 0 :(得分:5)

在C ++ 11中添加的

constexpr函数可以在编译时进行评估,并在模板元编程中用作模板参数。在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;

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

相关问题