gpt4 book ai didi

c++ - constexpr 和模板编译时间?

转载 作者:行者123 更新时间:2023-12-05 02:35:57 51 4
gpt4 key购买 nike

我有几个问题!我对 template 和 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?
}

最佳答案

你的 get_sum是一个函数模板。 get_sum<int>是一个几乎与任何其他函数一样的函数。不要被模板参数推导搞糊涂了,它确实发生在编译时。不扣你的main与以下内容完全相同:

constexpr int a=get_sum<int>(2,3);
const float b=get_sum<double>(2.2,3.2);
float c=get_sum<double>(2.2,3.2);

简而言之,模板在需要时由编译器实例化。一旦编译器合成了一个函数,例如 get_sum<int>这是一个像其他函数一样的函数,函数是否是constexpr与是否实例化模板的结果是正交的。

constexpr on a function 告诉编译器该函数可以在编译时求值。当在 constexpr 上下文中调用时,编译器必须在编译时评估它。例如constexpr int a在编译时初始化。 const float可能已经被编译器初始化了。甚至一个(非常量)float可能会被编译器完全优化掉。只要程序的可观察行为相同(实际上没有使用您的 3 个变量),就没有什么可以阻止编译器优化某些东西。

Ergo:

int main()
{
constexpr int a=get_sum(2,3); // get_sum<int> must be called at compile time
const float b=get_sum(2.2,3.2); // get_sum<double> is likely to be called at compile time
float c=get_sum(2.2,3.2); // get_sum<double> might be called at compile time or runtime
// or not at all, because the call does not
// contribute to observable behavior
}

长话短说

函数是否是函数模板的实例化,函数是否为constexpr是正交的。

关于c++ - constexpr 和模板编译时间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70383465/

51 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com