Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I make a templated conversion operator to `std::optional<T>`?

Tags:

c++

I'm using templated conversion operators to imitate return type deduction.

This normally works fine, except for when the target type is std::optional:

run on godbolt

#include <iostream>
#include <source_location>

struct A
{
    template <typename T>
    operator T() const
    {
        std::cout << std::source_location::current().function_name() << '\n';
        return 42;
    }
};

int main()
{
    int x = A{};                // `operator int`, ok
    std::optional<int> y = A{}; // `operator int`, but I want `operator std::optional<int>`
}

How can I make std::optional<int> y = A{}; call operator std::optional<int> instead of operator int? I understand why this happens (the optional<T> has a constructor that takes anything convertible to T), the question is how to fix it.

Adding a separate operator std::optional<T> doesn't work, unless I also remove operator T, but I'm trying to support all types with this.

like image 254
HolyBlackCat Avatar asked Feb 27 '26 01:02

HolyBlackCat


1 Answers

This is impossible: std::optional has a constructor template that (if viable) will always be a better match than any that would require a user-defined conversion. (The conversion to initialize the stored value happens later and does not count.)

like image 80
Davis Herring Avatar answered Mar 01 '26 15:03

Davis Herring



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!