【发布时间】:2022-01-19 19:21:19
【问题描述】:
我有几个问题!我对模板和 constexpr 及其区别感到困惑。
我知道模板是在编译时实例化的,它们是在编译时执行还是仅在运行时执行?有没有我可以一起使用它们来获得一些好处的例子?
如果我们有一个像本例中那样带有 constexpr 的模板会发生什么。
template <typename T>
constexpr T get_sum(T a, T b)
{
return a+b;
}
int main()
{
constexpr int a = get_sum(2,3); // compile time?
const float b = get_sum(2.2,3.2); // compile time?
float c = get_sum(2.2,3.2); // run time?
}
【问题讨论】: