{"id":13419285,"url":"https://github.com/mapbox/variant","last_synced_at":"2025-04-04T23:10:08.538Z","repository":{"id":14042063,"uuid":"16744626","full_name":"mapbox/variant","owner":"mapbox","description":"C++11/C++14 Variant","archived":false,"fork":false,"pushed_at":"2023-04-13T13:13:01.000Z","size":701,"stargazers_count":371,"open_issues_count":34,"forks_count":99,"subscribers_count":143,"default_branch":"master","last_synced_at":"2024-10-01T13:50:00.248Z","etag":null,"topics":["c-plus-plus"],"latest_commit_sha":null,"homepage":"","language":"C++","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"bsd-3-clause","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/mapbox.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null}},"created_at":"2014-02-11T20:37:24.000Z","updated_at":"2024-09-12T15:18:02.000Z","dependencies_parsed_at":"2022-09-25T21:52:59.927Z","dependency_job_id":"a4286e97-dc2d-48e4-a085-e2fcfff4bab0","html_url":"https://github.com/mapbox/variant","commit_stats":{"total_commits":483,"total_committers":21,"mean_commits":23.0,"dds":0.6625258799171843,"last_synced_commit":"f87fcbda9daf13fba47a6a889696b0ad23fc098d"},"previous_names":[],"tags_count":12,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mapbox%2Fvariant","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mapbox%2Fvariant/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mapbox%2Fvariant/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mapbox%2Fvariant/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/mapbox","download_url":"https://codeload.github.com/mapbox/variant/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":247261612,"owners_count":20910108,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["c-plus-plus"],"created_at":"2024-07-30T22:01:13.828Z","updated_at":"2025-04-04T23:10:08.520Z","avatar_url":"https://github.com/mapbox.png","language":"C++","readme":"# Mapbox Variant\n\nAn header-only alternative to `boost::variant` for C++11 and C++14\n\n[![Build Status](https://secure.travis-ci.com/mapbox/variant.svg?branch=master)](https://travis-ci.com/mapbox/variant)\n[![Build status](https://ci.appveyor.com/api/projects/status/v9tatx21j1k0fcgy)](https://ci.appveyor.com/project/Mapbox/variant)\n[![Coverage Status](https://coveralls.io/repos/mapbox/variant/badge.svg?branch=master\u0026service=github)](https://coveralls.io/r/mapbox/variant?branch=master)\n\n## Introduction\n\nVariant's basic building blocks are:\n\n- `variant\u003cTs...\u003e` - a type-safe representation for sum-types / discriminated unions\n- `recursive_wrapper\u003cT\u003e` - a helper type to represent recursive \"tree-like\" variants\n- `apply_visitor(visitor, myVariant)` - to invoke a custom visitor on the variant's underlying type\n- `get\u003cT\u003e()` - a function to directly unwrap a variant's underlying type\n- `.match([](Type){})` - a variant convenience member function taking an arbitrary number of lambdas creating a visitor behind the scenes and applying it to the variant\n\n### Basic Usage - HTTP API Example\n\nSuppose you want to represent a HTTP API response which is either a JSON result or an error:\n\n```c++\nstruct Result {\n  Json object;\n};\n\nstruct Error {\n  int32_t code;\n  string message;\n};\n```\n\nYou can represent this at type level using a variant which is either an `Error` or a `Result`:\n\n```c++\nusing Response = variant\u003cError, Result\u003e;\n\nResponse makeRequest() {\n  return Error{501, \"Not Implemented\"};\n}\n\nResponse ret = makeRequest();\n```\n\nTo see which type the `Response` holds you pattern match on the variant unwrapping the underlying value:\n\n```c++\nret.match([] (Result r) { print(r.object); },\n          [] (Error e)  { print(e.message); });\n```\n\nInstead of using the variant's convenience `.match` pattern matching function you can create a type visitor functor and use `apply_visitor` manually:\n\n```c++\nstruct ResponseVisitor {\n  void operator()(Result r) const {\n    print(r.object);\n  }\n\n  void operator()(Error e) const {\n    print(e.message);\n  }\n};\n\nResponseVisitor visitor;\napply_visitor(visitor, ret);\n```\n\nIn both cases the compiler makes sure you handle all types the variant can represent at compile.\n\n### Recursive Variants - JSON Example\n\n[JSON](http://www.json.org/) consists of types `String`, `Number`, `True`, `False`, `Null`, `Array` and `Object`.\n\n```c++\nstruct String { string value; };\nstruct Number { double value; };\nstruct True   { };\nstruct False  { };\nstruct Null   { };\nstruct Array  { vector\u003c?\u003e values; };\nstruct Object { unordered_map\u003cstring, ?\u003e values; };\n```\n\nThis works for primitive types but how do we represent recursive types such as `Array` which can hold multiple elements and `Array` itself, too?\n\nFor these use cases Variant provides a `recursive_wrapper` helper type which lets you express recursive Variants.\n\n```c++\nstruct String { string value; };\nstruct Number { double value; };\nstruct True   { };\nstruct False  { };\nstruct Null   { };\n\n// Forward declarations only\nstruct Array;\nstruct Object;\n\nusing Value = variant\u003cString, Number, True, False, Null, recursive_wrapper\u003cArray\u003e, recursive_wrapper\u003cObject\u003e\u003e;\n\nstruct Array {\n  vector\u003cValue\u003e values;\n};\n\nstruct Object {\n  unordered_map\u003cstring, Value\u003e values;\n};\n```\n\nFor walking the JSON representation you can again either create a `JSONVisitor`:\n\n```c++\nstruct JSONVisitor {\n\n  void operator()(Null) const {\n    print(\"null\");\n  }\n\n  // same for all other JSON types\n};\n\nJSONVisitor visitor;\napply_visitor(visitor, json);\n```\n\nOr use the convenience `.match` pattern matching function:\n\n```c++\njson.match([] (Null) { print(\"null\"); },\n           ...);\n```\n\nTo summarize: use `recursive_wrapper` to represent recursive \"tree-like\" representations:\n\n```c++\nstruct Empty { };\nstruct Node;\n\nusing Tree = variant\u003cEmpty, recursive_wrapper\u003cNode\u003e\u003e;\n\nstruct Node {\n  uint64_t value;\n}\n```\n\n### Advanced Usage Tips\n\nCreating type aliases for variants is a great way to reduce repetition.\nKeep in mind those type aliases are not checked at type level, though.\nWe recommend creating a new type for all but basic variant usage:\n\n```c++\n// the compiler can't tell the following two apart\nusing APIResult = variant\u003cError, Result\u003e;\nusing FilesystemResult = variant\u003cError, Result\u003e;\n\n// new type\nstruct APIResult : variant\u003cError, Result\u003e {\n  using Base = variant\u003cError, Result\u003e;\n  using Base::Base;\n}\n```\n\n## Why use Mapbox Variant?\n\nMapbox variant has the same speedy performance of `boost::variant` but is\nfaster to compile, results in smaller binaries, and has no dependencies.\n\nFor example on OS X 10.9 with clang++ and libc++:\n\nTest | Mapbox Variant | Boost Variant\n---- | -------------- | -------------\nSize of pre-compiled header (release / debug) | 2.8/2.8 MB         | 12/15 MB\nSize of simple program linking variant (release / debug)     | 8/24 K             | 12/40 K\nTime to compile header     | 185 ms             |  675 ms\n\n(Numbers from an older version of Mapbox variant.)\n\n## Goals\n\nMapbox `variant` has been a very valuable, lightweight alternative for apps\nthat can use c++11 or c++14 but that do not want a boost dependency.\nMapbox `variant` has also been useful in apps that do depend on boost, like\nmapnik, to help (slightly) with compile times and to majorly lessen dependence\non boost in core headers. The original goal and near term goal is to maintain\nexternal API compatibility with `boost::variant` such that Mapbox `variant`\ncan be a \"drop in\". At the same time the goal is to stay minimal: Only\nimplement the features that are actually needed in existing software. So being\nan \"incomplete\" implementation is just fine.\n\nCurrently Mapbox variant doesn't try to be API compatible with the upcoming\nvariant standard, because the standard is not finished and it would be too much\nwork. But we'll revisit this decision in the future if needed.\n\nIf Mapbox variant is not for you, have a look at [these other\nimplementations](doc/other_implementations.md).\n\nWant to know more about the upcoming standard? Have a look at our\n[overview](doc/standards_effort.md).\n\nMost modern high-level languages provide ways to express sum types directly.\nIf you're curious have a look at Haskell's pattern matching or Rust's and Swift's enums.\n\n## Depends\n\n- Compiler supporting `-std=c++11` or `-std=c++14`\n\nTested with:\n\n- g++-4.7\n- g++-4.8\n- g++-4.9\n- g++-5.2\n- clang++-3.5\n- clang++-3.6\n- clang++-3.7\n- clang++-3.8\n- clang++-3.9\n- Visual Studio 2015\n\n## Unit Tests\n\nOn Unix systems compile and run the unit tests with `make test`.\n\nOn Windows run `scripts/build-local.bat`.\n\n## Limitations\n\n- The `variant` can not hold references (something like `variant\u003cint\u0026\u003e` is\n  not possible). You might want to try `std::reference_wrapper` instead.\n\n## Deprecations\n\n- The included implementation of `optional` is deprecated and will be removed\n  in a future version. See [issue #64](https://github.com/mapbox/variant/issues/64).\n- Old versions of the code needed visitors to derive from `static_visitor`.\n  This is not needed any more and marked as deprecated. The `static_visitor`\n  class will be removed in future versions.\n\n## Benchmarks\n\n    make bench\n\n## Check object sizes\n\n    make sizes /path/to/boost/variant.hpp\n","funding_links":[],"categories":["TODO scan for Android support in followings","C++"],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmapbox%2Fvariant","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fmapbox%2Fvariant","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmapbox%2Fvariant/lists"}