개요
- n개의 타입들 중 하나를 보관할 수 있는 클래스
- 반드시 객체를 들고 있어야하며 초기화하지 않을 경우 첫번째 타입의 디폴트 생성자를 호출한 객체를 가짐
- monostate를 통해 아무것도 없는 상태 표현 가능
- holds_alternative 함수를 이용하여 특정 타입의 보관 유무 판단
- get_if 함수를 이용하여 특정 타입인 경우 접근 가능한 포인터 획득 가능
- visit 함수를 이용하여 보관된 타입을 몰라도 접근 가능
예제
- 코드
#include <iostream>
#include <string>
#include <variant>
#include <vector>
using namespace std;
int main() {
variant<monostate, int, double, string> v;
v = 1;
cout << get<int>(v) << endl;
cout << v.index() << endl;
cout << holds_alternative<int>(v) << endl;
cout << holds_alternative<double>(v) << endl;
cout << holds_alternative<string>(v) << endl;
cout << "------ 1" << endl;
v = 1.1;
cout << get<double>(v) << endl;
cout << v.index() << endl;
cout << holds_alternative<int>(v) << endl;
cout << holds_alternative<double>(v) << endl;
cout << holds_alternative<string>(v) << endl;
cout << "------ 2" << endl;
v = "abc";
cout << get<string>(v) << endl;
cout << v.index() << endl;
cout << holds_alternative<int>(v) << endl;
cout << holds_alternative<double>(v) << endl;
cout << holds_alternative<string>(v) << endl;
cout << "------ 3" << endl;
if (get_if<string>(&v)) {
cout << get<string>(v) << endl;
}
cout << "------ 4" << endl;
struct Visitor {
void operator()(std::monostate arg) { cout << "monostate" << endl; }
void operator()(int arg) { cout << arg << endl; }
void operator()(double arg) { cout << arg << endl; }
void operator()(string arg) { cout << arg << endl; }
};
vector<variant<monostate, int, double, string>> vv{"abc", 1, 1.1};
for (const auto &iter : vv) {
visit(Visitor{}, iter);
}
return 0;
}
- 실행 결과
1
1
1
0
0
------ 1
1.1
2
0
1
0
------ 2
abc
3
0
0
1
------ 3
abc
------ 4
abc
1
1.1