/variant-lite

A single-file header-only version of a C++17-like variant, a type-safe union for C++98, C++11 and later

Primary LanguageC++Boost Software License 1.0BSL-1.0

variant lite: A single-file header-only version of a C++17-like variant, a type-safe union for C++98, C++11 and later

Standard License Build Status Build status Version Latest download Conan Try it online

Contents

Example usage

#include "variant.hpp"

#include <cassert>
#include <string>

using namespace nonstd;

int main()
{
    std::string hello = "hello, world"; 

    variant< char, int, long, std::string > var;
    
    var =  'v' ; assert( get<  0 >( var ) == 'v' );
                 assert( get<char>( var ) == 'v' );
    var =   7  ; assert( get<int >( var ) ==  7  );
    var =  42L ; assert( get<long>( var ) == 42L );    
    var = hello; assert( get<std::string>( var ) == hello );
}

Compile and run

prompt>g++ -std=c++98 -Wall -I../include/nonstd -o 01-basic.exe 01-basic.cpp && 01-basic.exe

In a nutshell

variant lite is a single-file header-only library to represent a type-safe union. The library aims to provide a C++17-like variant for use with C++98 and later. If available, std::variant is used.

Features and properties of variant lite are ease of installation (single header), freedom of dependencies other than the standard library and control over object alignment (if needed). variant lite shares the approach to in-place tags with any-lite and with optional-lite and these libraries can be used together.

Limitations of variant lite are the maximum of seven alternative types that all must have a different type. Move construction, move assignment and emplacement require C++11 and are not supported when compiling under C++98. The visitor only takes a single variant and can only return a variant. variant lite does not provide allocator-extended constructors.

License

variant lite is distributed under the Boost Software License.

Dependencies

variant lite has no other dependencies than the C++ standard library.

Installation

variant lite is a single-file header-only library. Put variant.hpp in the include folder directly into the project source tree or somewhere reachable from your project.

Or, if you use the conan package manager, follow these steps:

  1. Add nonstd-lite to the conan remotes:

     conan remote add nonstd-lite https://api.bintray.com/conan/agauniyal/nonstd-lite
    
  2. Add a reference to variant-lite to the requires section of your project's conanfile.txt file:

     [requires]
     variant-lite/0.1.0@nonstd-lite/stable
    
  3. Run conan's install command:

     conan install
    

Synopsis

Contents

Types in namespace nonstd

Purpose Type Notes
Type-safe union template< class T0...T6 >
class variant
non-standard: may hold up to seven types
Default constructible class monostate Type to make variant default constructible
Error reporting class bad_variant_access  
In-place construction struct in_place_tag  
  in_place select type or index for in-place construction
  in_place_type select type for in-place construction
  in_place_index select index for in-place construction
  nonstd_lite_in_place_type_t( T) macro for alias template in_place_type_t<T>
  nonstd_lite_in_place_index_t( T ) macro for alias template in_place_index_t<T>
Variant size template<...>
struct variant_size< variant<...> >
 
  variant_size_v< T > C++14
  variant_size_V( T ) macro for nonstd::variant_size<T>::value
Select variant type template< std::size_t I, ...>
struct variant_alternative< I, variant<...> >
 
  variant_alternative_t< I, T > C++11
  variant_alternative_T( I, T ) macro for typename nonstd::variant_alternative<I,T >::type

Interface of variant lite

Kind Std Method Result
Construction   variant() default-construct first type
    variant( Tx const & x ) copy-construct with value type Tx
  C++11 variant( Tx && x ) move-construct with value type Tx
    variant( variant const & rhs ) copy-construct from other variant
  C++11 variant( variant && rhs ) move-construct from other variant
  C++11 template< class T, class... Args >
explicit variant( in_place_type_t(T), Args&&... args)
in-place-construct type T
  C++11 template< class T, class U, class... Args >
explicit variant( in_place_type_t(T),
 std::initializer_list<U> il, Args&&... args )
in-place-construct type T
  C++11 template< std::size_t I, class... Args >
explicit variant( in_place_index_t(I), Args&&... args )
in-place-construct type at index I
  C++11 template< size_t I, class U, class... Args>
explicit variant( in_place_index_t(I),
 std::initializer_list<U> il, Args&&... args )
in-place-construct type at index I
Destruction   ~variant() destruct current content
Assignment   variant & operator=( variant const & rhs ) copy-assign from other
  C++11 variant & operator=( variant && rhs ) move-assign from other
  C++11 template< class Tx >
variant & operator=( Tx && t )
move-assign from value
  < C++11 template< class Tx >
variant & operator=( Tx const & t )
copy-assign from value;
non-standard
State   std::size_t index() const index of current content's type
    bool valueless_by_exception() const true if no content is present
Emplace C++11 template< class T, class... Args >
void emplace( Args&&... args )
emplace type T
  C++11 template< class T, class U, class... Args >
void emplace( std::initializer_list<U> il, Args&&... args )
emplace type T
  C++11 template< size_t I, class... Args >
void emplace( Args&&... args );
emplace type at index I
  C++11 template< size_t I, class U, class... Args >
void emplace( std::initializer_list<U> il, Args&&... args )
emplace type at index I
Swap   void swap( variant & other ); swap with other

Algorithms for variant lite

Kind Std Function
Relational operators    
==   template<...>
bool operator==( variant<...> const & v, variant<...> const & w )
!=   template<...>
bool operator==( variant<...> const & v, variant<...> const & w )
<   template<...>
bool operator<( variant<...> const & v, variant<...> const & w )
>   template<...>
bool operator>( variant<...> const & v, variant<...> const & w )
<=   template<...>
bool operator<=( variant<...> const & v, variant<...> const & w )
>=   template<...>
bool operator>=( variant<...> const & v, variant<...> const & w )
Content    
contains value of type T   template< class T, ...>
bool holds_alternative( variant<...> const & v ) [noexcept]
get by type   template< class R, ...>
R &
get( variant<...> & v, in_place_type_t(R) = in_place )
get by type (const)   template< class R, ...>
R const &
get( variant<...> const & v, in_place_type_t(R) = in_place )
get by index   template< std::size_t I, ...>
typename variant_alternative< I, variant<...> >::type &
get( variant<...> & v, in_place_index_t(I) = in_place )
get by index (const)   template< std::size_t I, ...>
typename variant_alternative< I, variant<...> >::type const &
get( variant<...> const & v, in_place_index_t(I) = in_place )
get_if by type   template< class T, ...>
typename detail::add_pointer<T>::type
get_if( variant<...> * pv, in_place_type_t(T) = in_place )
get_if by type (const)   template< class T, ...>
typename detail::add_pointer<const T>::type
get_if( variant<...> const * pv, in_place_type_t(T) = in_place)
get_if by index   template< std::size_t I, ...>
typename detail::add_pointer< typename variant_alternative<I, variant<T0, T1, T2, T3, T4, T5, T6> >::type >::type
get_if( variant<...> * pv, in_place_index_t(I) = in_place )
get_if by index (const)   template< std::size_t I, ...>
typename detail::add_pointer< const typename variant_alternative<I, variant<T0, T1, T2, T3, T4, T5, T6> >::type >::type
get_if( variant<...> const * pv, in_place_index_t(I) = in_place )
swap   template<...>
void swap( variant<...> & x, variant<...> & y )
visit Note 1 template< class Visitor, class Variant >
Variant visit( Visitor const & vis, Variant const & v )
Hash support    
variant C++11 template<...> struct hash< variant<...> >;
monostate C++11 template<> struct hash< monostate >;

Note 1: visitor is limited to always return a Variant.

Configuration macros

-Dvariant_CONFIG_OMIT_VARIANT_SIZE_V_MACRO=0
Define this macro to 1 to omit the variant_size_V(T) macro. Default is 0.

-Dvariant_CONFIG_OMIT_VARIANT_ALTERNATIVE_T_MACRO=0
Define this macro to 1 to omit the variant_alternative_T(I,T) macro. Default is 0.

Macros to control alignment

If variant lite is compiled as C++11 or later, C++11 alignment facilities are used for storage of the underlying object. When compiled as pre-C++11, variant lite tries to determine proper alignment itself. If this doesn't work out, you can control alignment via the following macros. See also section Implementation notes.

-Dvariant_CONFIG_MAX_ALIGN_HACK=0
Define this to 1 to use the max align hack for alignment. Default is 0.

-Dvariant_CONFIG_ALIGN_AS=pod_type
Define this to the pod-type you want to align to (no default).

-Dvariant_CONFIG_ALIGN_AS_FALLBACK=pod_type
Define this to the pod-type to use for alignment if the algorithm of variant lite cannot find a suitable POD type to use for alignment. Default is double.

Reported to work with

The table below mentions the compiler versions variant lite is reported to work with.

OS Compiler Versions
Windows Clang/LLVM ?
  GCC 5.2.0
  Visual C++
(Visual Studio)
8 (2005), 10 (2010), 11 (2012),
12 (2013), 14 (2015)
GNU/Linux Clang/LLVM 3.5.0
  GCC 4.8.4
OS X ? ?

Building the tests

To build the tests you need:

The lest test framework is included in the test folder.

The following steps assume that the variant lite source code has been cloned into a directory named c:\variant-lite.

  1. Create a directory for the build outputs for a particular architecture. Here we use c:\variant-lite\build-win-x86-vc10.

     cd c:\variant-lite
     md build-win-x86-vc10
     cd build-win-x86-vc10
    
  2. Configure CMake to use the compiler of your choice (run cmake --help for a list).

     cmake -G "Visual Studio 10 2010" ..
    
  3. Build the test suite in the Debug configuration (alternatively use Release).

     cmake --build . --config Debug
    
  4. Run the test suite.

     ctest -V -C Debug
    

All tests should pass, indicating your platform is supported and you are ready to use variant lite.

Implementation notes

Object allocation and alignment

variant lite reserves POD-type storage for an object of the underlying type inside a union to prevent unwanted construction and uses placement new to construct the object when required. Using non-placement new (malloc) to obtain storage, ensures that the memory is properly aligned for the object's type, whereas that's not the case with placement new.

If you access data that's not properly aligned, it 1) may take longer than when it is properly aligned (on x86 processors), or 2) it may terminate the program immediately (many other processors).

Although the C++ standard does not guarantee that all user-defined types have the alignment of some POD type, in practice it's likely they do [10, part 2].

If variant lite is compiled as C++11 or later, C++11 alignment facilities are used for storage of the underlying object. When compiling as pre-C++11, variant lite tries to determine proper alignment using meta programming. If this doesn't work out, you can control alignment via three macros.

variant lite uses the following rules for alignment:

  1. If the program compiles as C++11 or later, C++11 alignment facilities are used.

  2. If you define -Dvariant_CONFIG_MAX_ALIGN_HACK=1 the underlying type is aligned as the most restricted type in struct max_align_t. This potentially wastes many bytes per variant if the actually required alignment is much less, e.g. 24 bytes used instead of the 2 bytes required.

  3. If you define -Dvariant_CONFIG_ALIGN_AS=pod-type the underlying type is aligned as pod-type. It's your obligation to specify a type with proper alignment.

  4. If you define -Dvariant_CONFIG_ALIGN_AS_FALLBACK=pod-type the fallback type for alignment of rule 5 below becomes pod-type. It's your obligation to specify a type with proper alignment.

  5. At default, variant lite tries to find a POD type with the same alignment as the underlying type.

    The algorithm for alignment of 5. is:

    • Determine the alignment A of the underlying type using alignment_of<>.
    • Find a POD type from the list alignment_types with exactly alignment A.
    • If no such POD type is found, use a type with a relatively strict alignment requirement such as double; this type is specified in variant_CONFIG_ALIGN_AS_FALLBACK (default double).

Note that the algorithm of 5. differs from the one Andrei Alexandrescu uses in [10, part 2].

The class template alignment_of<> is gleaned from Boost.TypeTraits, alignment_of [14].

For more information on constructed unions and alignment, see [10-14].

Other implementations of variant

Notes and References

References

[1] CppReference. Variant.

[2] ISO/IEC WG21. N4606, section 20.7 Variants. July 2016.

[3] Axel Naumann. Variant: a type-safe union for C++17 (v8). June 2016.

[4] Peter Dimov. Valueless Variants Considered Harmful. March 2016.

[5] Anthony Williams. Standardizing Variant: Difficult Decisions. June 2015

[6] Andrzej Krzemieński. Constexpr unions. December 2012.

[7] Agustín Bergé. Eggs.Variant - Part I. August 2014.

[8] Agustín Bergé. Eggs.Variant - Part II (the constexpr experience). March 2015.

[9] Andrei Alexandrescu. An Implementation of Discriminated Unions in C++. August 2002.

[10] Andrei Alexandrescu. Generic: Discriminated Unions part 1, part 2, part 3. April 2002.

[11] Herb Sutter. Style Case Study #3: Construction Unions. GotW #85. 2009

[12] Kevin T. Manley. Using Constructed Types in C++ Unions. C/C++ Users Journal, 20(8), August 2002.

[13] StackOverflow. Determining maximum possible alignment in C++.

[14] Boost.TypeTraits, alignment_of ( code ).

Presentations

[15] Ben Deane. Using Types Effectively. CppCon 2016.

Appendix

A.1 Variant Lite test specification

variant: Disallows non-default constructible as first type
variant: Allows non-default constructible as second and later type (first: int)
variant: Allows non-default constructible as second and later type (first: monostate)
variant: Allows to default-construct variant
variant: Allows to copy-construct from variant
variant: Allows to move-construct from variant (C++11)
variant: Allows to obtain the index of the current type
variant: Allows to inspect if variant is "valueless by exception"
variant: Allows to copy-assign from variant
variant: Allows to copy-assign mutually empty variant
variant: Allows to copy-assign from empty variant
variant: Allows to copy-assign to empty variant
variant: Allows to move-assign from variant (C++11)
variant: Allows to move-assign mutually empty variant (C++11)
variant: Allows to move-assign from empty variant (C++11)
variant: Allows to move-assign to empty variant (C++11)
variant: Allows to construct from element value
variant: Allows to copy-construct from element
variant: Allows to move-construct from element (C++11)
variant: Allows to convert-copy-construct from element
variant: Allows to convert-move-construct from element (C++11)
variant: Allows to copy-assign from element value
variant: Allows to move-assign from element value
variant: Allows to copy-assign from element
variant: Allows to move-assign from element (C++11)
variant: Allows to convert-copy-assign from element value
variant: Allows to copy-construct from elements in intializer-list based on type (C++11)
variant: Allows to move-construct from elements in intializer-list based on type (C++11)
variant: Allows to in-place copy-construct element based on type (C++11)
variant: Allows to in-place move-construct element based on type (C++11)
variant: Allows to in-place copy-construct element based on index (C++11)
variant: Allows to in-place move-construct element based on index (C++11)
variant: Allows to in-place copy-construct elements from intializer-list based on type (C++11)
variant: Allows to in-place move-construct elements from intializer-list based on type (C++11)
variant: Allows to in-place copy-construct elements from intializer-list based on index (C++11)
variant: Allows to in-place move-construct elements from intializer-list based on index (C++11)
variant: Allows to copy-emplace element based on type (C++11)
variant: Allows to move-emplace element based on type (C++11)
variant: Allows to copy-emplace element based on index (C++11)
variant: Allows to move-emplace element based on index (C++11)
variant: Allows to copy-emplace elements from intializer-list based on type (C++11)
variant: Allows to move-emplace elements from intializer-list based on type (C++11)
variant: Allows to copy-emplace elements from intializer-list based on index (C++11)
variant: Allows to move-emplace elements from intializer-list based on index (C++11)
variant: Allows to swap variants, same index (member)
variant: Allows to swap variants, different index (member)
variant: Allows to visit contents (non-standard: always returning variant)
variant: Allows to check for content by type
variant: Allows to get element by type
variant: Allows to get element by index
variant: Allows to get pointer to element or NULL by type
variant: Allows to get pointer to element or NULL by index
variant: Allows to compare variants
variant: Allows to swap variants, same index (non-member)
variant: Allows to swap variants, different index (non-member)
monostate: Allows to make variant default-constructible
bad_variant_access: Indicates invalid variant access
variant_size<>: Allows to obtain number of element types (non-standard: max 7)
variant_size_v<>: Allows to obtain number of element types (C++14, non-standard: max 7)
variant_size_V(): Allows to obtain number of element types (non-standard: max 7, macro)
variant_alternative<>: Allows to select type by index
variant_alternative_t<>: Allows to select type by index (C++11)
variant_alternative_T(): Allows to select type by index (non-standard: macro)
std::hash<>: Allows to obtain hash (C++11)