Skip to content

[BUG] is type for std::optional can return unexpected results #1328

@bluetarpmedia

Description

@bluetarpmedia

Describe the bug
An expression testing if a std::optional is a type can return unexpected results, depending on whether the optional's type is convertible to the target type. (I'm assuming this behaviour is unintended.)

To Reproduce
Run cppfront on the following and then compile with a C++ compiler:

main: () -> int = {
    o: std::optional<int> = 5;
    if o is int {
        std::cout << "int!\n";
    }
    if o is bool {
        std::cout << "bool!\n";
    }
    if o is float {
        std::cout << "float!\n";
    }
    if o is std::string {
        std::cout << "std::string!\n";
    }
    return 0;
}

The output is:

int!
bool!
float!

Repro on Godbolt.

I think this behaviour is due to this cast:

if constexpr (requires { static_cast<const T&>(*x);}) {

CC @filipsajdak

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions