无法在std :: variant中采用相同类型 [英] Unable to take same type in std::variant

查看:100
本文介绍了无法在std :: variant中采用相同类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用c ++ 17,并且想编写类似这样的代码,

I'm using c++17, and would like to write the code something like this,

#include <variant>
typedef int NewInt;
int main() {
    std::variant<NewInt, int> n = 1;
}

但是它会产生编译错误,

But it emits compile error,

po.cpp: In function ‘int main()’:
po.cpp:5:35: error: conversion from ‘int’ to non-scalar type ‘std::variant<int, int>’ requested
     std::variant<NewInt, int> n = 1;
                               ^

我如何定义 std之类的类型: variant< NewInt,int> 还是不可能?

How could I define the type like std::variant<NewInt, int> or is it impossible?

推荐答案

类型别名只是另一个名字对于现有类型,而不是新类型。因此,您有两个int的变体。并且在允许的情况下,您必须明确解决歧义。 std :: variant 具有合适的构造函数:

A type alias is just another name for an existing type, not a new type. So you have a variant of two ints. And while it's allowed, you must address the ambiguity explicitly. std::variant has a suitable constructor:

std::variant<NewInt, int> n{ std::in_place_index<0>, 1 };

以上将构造第一个整数成员(您的 NewInt )。如果要构造第二个,则很明显:

The above will construct the first integer member (your NewInt). If you want to construct the second, it's the obvious:

std::variant<NewInt, int> n{ std::in_place_index<1>, 1 };

这篇关于无法在std :: variant中采用相同类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆