CodexBloom - Programming Q&A Platform

Inconsistent behavior with std::optional and std::variant in C++20 when using constexpr functions

πŸ‘€ Views: 0 πŸ’¬ Answers: 1 πŸ“… Created: 2025-06-12
c++20 optional variant constexpr C++

I'm working on a project and hit a roadblock. I'm getting frustrated with I'm trying to configure Hey everyone, I'm running into an issue that's driving me crazy. I'm experiencing inconsistent behavior when trying to use `std::optional` and `std::variant` together with `constexpr` in C++20. I have a function that returns a `std::optional<std::variant<int, std::string>>` based on some input, but when I try to call this function in a `constexpr` context, I'm running into issues. Here's the relevant code snippet: ```cpp #include <optional> #include <variant> #include <string> #include <iostream> constexpr std::optional<std::variant<int, std::string>> getValue(int input) { if (input < 0) { return std::nullopt; } else if (input == 0) { return std::variant<int, std::string>{"Zero"}; } else { return std::variant<int, std::string>{input}; } } int main() { constexpr auto result = getValue(0); if (result.has_value()) { std::visit([](auto&& arg) { std::cout << arg << '\n'; }, *result); } else { std::cout << "No value" << '\n'; } return 0; } ``` When I compile this with GCC 11.2.0, I get an behavior like: ``` behavior: calling a constexpr function β€˜getValue’ that is not marked constexpr ``` I checked the return type and the function itself is marked as `constexpr`, so I need to understand why this is happening. I've also tried simplifying the return types and the logic, but the behavior continues. Is there something specific about using `std::variant` or `std::optional` in `constexpr` functions that I might be missing? I've attempted to create similar functions with only one of the two types, and they compile fine. However, combining them seems to throw this behavior. Any insights would be appreciated. This is part of a larger CLI tool I'm building. I'm working with C++ in a Docker container on Debian. Could this be a known issue? I've been using C++ for about a year now.