模板函数是否以内联方式声明 constexpr,即使实例化不是 constexpr

Does template function declared constexpr allways inline even if instantiation is not constexpr?

本文关键字:constexpr 实例化 声明 方式 函数 是否      更新时间:2023-10-16

根据这个答案,constexpr函数总是inline

模板函数可以声明为constexpr,即使所有专用化都不满足成为constexpr函数的要求。在最后一种情况下,专业化不是constexpr .

例如:

template<class T>
constexpr decltype(auto) size(const T& a){
   return a.size();
}
std::array<int,10> arr;
std::vector<int> vec;
size(arr);//constexpr
size(vec);//not a constexpr;
实例

size<std::vector>不是constexpr,但它是inline吗?

是的;引用N4640,[dcl.constexpr]/1:

constexpr说明符声明的函数或静态数据成员隐式是内联函数或变量。

这里的关键是"声明"——声明才是重要的,而不是满足constexpr要求。