Speclib  0.1.2
The library for writing better CUDA libraries
sp::Variant< T, Ts > Union Template Reference

Reimplementation of std::variant for GPU. More...

#include <Variant.hpp>

Public Member Functions

template<typename Q >
constexpr auto operator= (Q &&input)
 Assign a value. More...
 
template<typename Q >
constexpr auto get ()
 Access the unique element of the given type, if it exists. More...
 
template<int I>
constexpr auto get ()
 Get by index. More...
 
template<typename Q >
 Variant (Q &&v)
 

Detailed Description

template<typename T, typename... Ts>
union sp::Variant< T, Ts >

Reimplementation of std::variant for GPU.

Variants are conceptually similar to unions. They allow you to reuse the same region of memory to store different and type-incompatible objects at different times. Provided the lifetimes of the objects don't overlap, this is safe.

This is particularly useful for reusing __shared__ memory when GPU programming.

Although you cannot put arrays directly into Variants, you can use sp::Vec or sp::StaticTensor instead. These are preferable to bare arrays in all cases because they provide handy bounds-checking in debug builds.

Example

// The Variant occupies as much memory as its largest member.
static_assert(sizeof(v) == sizeof(sp::Vec<int, 4>));
// Store a Vec in the variant. If it was previously storing an int/float, it is lost.
v = sp::Vec<int, 4>{1, 4, 2, 6};
// We can read back our stored Vec by member-position...
auto readVec = v.template get<2>(); // [1, 4, 2, 6]
// ... Or by type:
auto readVecAgain = v.template get<sp::Vec<int, 4>>(); // [1, 4, 2, 6]
// We're done with the Vec. Let's reuse the same memory to store an int:
v = 1;
EXPECT_EQ(1, v.template get<0>());
EXPECT_EQ(1, v.template get<int>());
// And again with the float:
v = 42.0f;
EXPECT_EQ(42.0f, v.template get<1>());
EXPECT_EQ(42.0f, v.template get<float>());
A vector of S elements of type T.
Definition: Vec.hpp:71
Reimplementation of std::variant for GPU.
Definition: Variant.hpp:30

Member Function Documentation

◆ get() [1/2]

template<typename T , typename... Ts>
template<typename Q >
constexpr auto sp::Variant< T, Ts >::get ( )
constexpr

Access the unique element of the given type, if it exists.

◆ get() [2/2]

template<typename T , typename... Ts>
template<int I>
constexpr auto sp::Variant< T, Ts >::get ( )
constexpr

Get by index.

◆ operator=()

template<typename T , typename... Ts>
template<typename Q >
constexpr auto sp::Variant< T, Ts >::operator= ( Q &&  input)
constexpr

Assign a value.