c++gccc++17std-variant

gcc 10 refuse implict conversions for std::variant constructor


for this simple code

#include <vector>
#include <variant>
#include <stdint.h>

using KFPGAData = std::variant<uint16_t>;


int main(int,char**)
{
    int v = 10;
    KFPGAData d = v;

    return 0;
}

use gcc compile it with -std=c++17

compilation passed for gcc9, but failed for gcc10 above:

<source>:11:19: error: conversion from 'int' to non-scalar type 'KFPGAData' {aka 'std::variant<short unsigned int>'} requested
   11 |     KFPGAData d = v;
      |                   ^

why is this happen? I try other high version compiler for msvc and clang, all of them produced the similar error

link: https://godbolt.org/z/1M9xKd9fj


Solution

  • From https://en.cppreference.com/w/cpp/utility/variant/variant emphasis mine:

    Converting constructor. Constructs a variant holding the alternative type T_j that would be selected by overload resolution for the expression F(std::forward<T>(t)) if there was an overload of imaginary function F(T_i) for each T_i in Types..., except that narrowing conversions aren't considered.

    Note that narrowing conversion not considered comes from Defect reports. See p0608r3.