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?
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.
Since this function is specific to a given type, you don't need RTTI to perform the operations required by std::any .
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.
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.
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 };
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With