MSVC(STD:C+ 17)可选始终返回值
我正在为射线示踪剂编写一些交叉代码。在计算球体的一些交点逻辑之后,我想返回可选的,以确定是否存在相交。我不想返回距离的“无效”值,而是要使用C ++'S std ::可选
类。唯一的问题是,它似乎总是返回true
for has_value()
:
std::optional<Intersection> Sphere::ray_intersection(Ray ray)
// Calculate Intersection Logic
// ...
if (distance_to_intersection < 0) {
return std::nullopt;
} else {
return Intersection(ray, distance_to_intersection);
}
}
返回后,我使用以下代码检查:
if (sphere.ray_intersection(ray).has_value()) {
return shade(sphere, intersection);
} else {
return background_color;
}
我知道实际的交叉点逻辑正确,因为当我替换返回std :: nullopt;
用返回交叉点(ray,-1);
(无效距离),然后简单地检查距离是否等于-1
在上一个检查中,它的行为符合预期。
我还尝试返回简单的{}
无用。
我目前正在使用Microsoft Visual Studio 2022,并且我尝试了C ++ 17和C ++ 20编译器,并且我期望的是行为。
std ::可选
操作我不知道的特定方式吗?
I'm writing some intersection code for a Ray tracer. After calculating some intersection logic for a sphere, I want to return an optional to determine if there was an intersection or not. Instead of returning an "invalid" value for distance, I want to use C++'s std::optional
class. The only issue is that it seems to always return true
for has_value()
:
std::optional<Intersection> Sphere::ray_intersection(Ray ray)
// Calculate Intersection Logic
// ...
if (distance_to_intersection < 0) {
return std::nullopt;
} else {
return Intersection(ray, distance_to_intersection);
}
}
After returning, I check using the following code:
if (sphere.ray_intersection(ray).has_value()) {
return shade(sphere, intersection);
} else {
return background_color;
}
I know the actual intersection logic works correctly, because when I replace return std::nullopt;
with return Intersection(ray, -1);
(an invalid distance) and then simply check if the distance is equal to -1
in the previous if
check, it behaves as expected.
I've also tried returning a simple {}
to no avail.
I'm currently using Microsoft Visual Studio 2022, and I have tried both the C++17 and C++20 compilers, and neither will behave as I'm expecting.
Is there a specific way that std::optional
operates that I'm not aware of?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论