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?
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 };
来源:https://stackoverflow.com/questions/47858965/unable-to-take-same-type-in-stdvariant