提问人:Alex Vergara 提问时间:11/12/2023 更新时间:11/14/2023 访问量:110
在 constexpr 表达式中使用 this ptr
Using the this ptr in a constexpr expression
问:
我有两种类型,一种用于定义数字(正整数 >= 1),另一种用于定义整数(任何整数值或整数)。Natural
尝试实现 ,如果减法值< 1,我想返回一个 Integer 而不是 Natural。所以这是我的尝试:operator-(const Natural rhs)
[[nodiscard]] constexpr auto Natural::operator-(const Natural& rhs) const noexcept
-> std::conditional_t<(_number > rhs.number() + 1), Natural, Integer>
{
if constexpr(_number > rhs.number() + 1)
return Natural(_number - rhs.number());
else
return Integer(static_cast<int>(_number) - static_cast<int>(rhs.number()));
}
但是 Clang-Tidy 告诉我不允许在 constexpr 分支中使用隐式 this ptr,因为该值在编译时是未知的。 这是有道理的,但我不知道如何使用 SFINAE 以外的其他工具解决这种情况,我试图避免这种情况,因为使用更复杂,代码库应该尽可能简单。
那么,有什么方法可以解决这个问题,并能够在编译时丢弃其中一个分支呢?
注意:自然类型只是一个包装器,而不是一个unsigned int
答: 暂无答案
评论
consteval
constexpr
std::variant<Natural,Integer>