小编Joe*_*ber的帖子

为什么将 int 分配给 std::variant<long int, ...> 失败?

在分配给变体时,我觉得我遗漏了一些关于 int 类型提升的明显信息。

在 gcc 9.3.0 版本(Ubuntu 9.3.0-11ubuntu0~18.04.1)上,使用 -std=c++17 编译,以下代码编译失败:

#include <variant>
#include <iostream>

int main()
    {
    std::variant<long int, bool> v;  // works fine if "long" is omitted
    long int sanity = 1;             // verify that we can assign 1 to a long int; works fine

    std::cout << sizeof(sanity) << "\n";

    v = 1;                           // compiler error here: why doesn't this assign to the long int variant of v?

    return 0;
    }
Run Code Online (Sandbox Code Playgroud)

错误信息:

error: no match for ‘operator=’ (operand types …
Run Code Online (Sandbox Code Playgroud)

c++ c++17 std-variant

3
推荐指数
1
解决办法
111
查看次数

标签 统计

c++ ×1

c++17 ×1

std-variant ×1