https://gcc.gnu.org/bugzilla/show_bug.cgi?id=113060

            Bug ID: 113060
           Summary: std::variant converting constructor/assignment is
                    non-conforming after P2280?
           Product: gcc
           Version: 14.0
            Status: UNCONFIRMED
          Severity: normal
          Priority: P3
         Component: libstdc++
          Assignee: unassigned at gcc dot gnu.org
          Reporter: dangelog at gmail dot com
  Target Milestone: ---

GCC 14 implements P2280 (see #106650). 

As a side effect of that, the "narrowing detector" used in std::variant's
converting constructor/assignment is now too restrictive. This code:


    // IC is a type with a constexpr conversion operator
    using IC = std::integral_constant<int, 42>;
    std::variant<float> v( IC{} );

should work after P2280 (libstdc++ says ill-formed).

---

https://eel.is/c++draft/variant.ctor#14 says:

> Let Tj be a type that is determined as follows: build an imaginary function 
> FUN(Ti) for each alternative type Ti for which Ti x[] = 
> {std​::​forward<T>(t)}; is well-formed for some invented variable x.
> The overload FUN(Tj) selected by overload resolution for the expression 
> FUN(std​::​forward<T>(​t)) defines the alternative Tj which is the type of 
> the contained value after construction.


Right now libstdc++ implements this by means of SFINAE:

> https://github.com/gcc-mirror/gcc/blob/master/libstdc%2B%2B-v3/include/std/variant#L787-L823


IC is convertible to float, and given the constexpr nature of its conversion
operator (to int), it wouldn't be a narrowing conversion:

  IC ic;
  float f{ic}; // not narrowing

However, using SFINAE means that std::declval<IC>() is used to build the
"candidate" argument of FUN. declval is not a constexpr function so its
returned value is not considered to be usable in constant expressions. 

The net effect is that `Ti x[] = {std​::​forward<T>(t)};` is considered to be a
narrowing conversion ([dcl.init.list], int->float, source is not a constant
expression), and FUN(float) rejected.

But nowhere does [variant.ctor] talk about using std::declval; if one
reimplements the same check with a constraint, then GCC 14 accepts the
conversion:

    template <typename Tj, typename T>
    concept FUN_constraint = requires(T &&t) {
        { std::type_identity_t<Tj[]>{ std::forward<T>(t) } };
    };

    template <typename T>
    requires FUN_constraint<float, T>
    void FUN(float);

    FUN<IC>( IC{} ); // OK

https://gcc.godbolt.org/z/xP9z97v35

P2280 is necessary to make this work, because otherwise the usage of a
reference in the requires-expression would make `t` again not usable in
constant expressions. In conclusion, it seems that variant<float> should indeed
accept construction from IC.

(I can't cross-check this report with other compilers as none of them
implements P2280 yet.)

Reply via email to