我试图将shared_ptr传递到模板化函数中并在该函数内取消引用它。例如:
constexpr bool test(std::shared_ptr<Type>&val) const
{
return val->some_bool;
}
除了在传入之前取消引用它之外,还有一种方法可以在 constexpr 内取消引用智能指针吗?
您可以在 constexpr 函数中调用任何您想要的函数。但是,这并不意味着 constexpr 函数实际上可以在编译时求值。在编译时,只能调用 constexpr 函数,因此如果 constexpr 函数调用非 constexpr 函数,则前者无法在编译时求值。
operator*
和operator->
函数,以及数组情况下的operator[]
(用于引用shared_ptr
)不是constexpr
,因此无法在编译时调用。而且,正如评论中所指出的,shared_ptr
没有构造函数甚至允许您首先创建一个非空constexpr
shared_ptr
,或者在以下位置创建一个非空shared_ptr
编译时间。