Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to take same type in std::variant

Tags:

c++

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;
                               ^

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

like image 359
kriw Avatar asked Dec 17 '17 20:12

kriw


People also ask

Does std :: variant allocate?

One additional thing is that std::variant does not dynamically allocate memory for the values. Any instance of std::variant at any given time either holds a value of one of its alternative types, or it holds no value at all.

Does STD variant use RTTI?

Since this function is specific to a given type, you don't need RTTI to perform the operations required by std::any .

How do you compare STD variants?

A given instance of std::variant compares equal to another if and only if they hold the same variant alternative and said alternatives' values compare equal.

Can std :: variant be empty?

Empty variants are also ill-formed (std::variant<std::monostate> can be used instead). A variant is permitted to hold the same type more than once, and to hold differently cv-qualified versions of the same type.


1 Answers

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 };

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 };
like image 159
StoryTeller - Unslander Monica Avatar answered Sep 27 '22 20:09

StoryTeller - Unslander Monica