Skip to content

Instantly share code, notes, and snippets.

@kudaba
Last active August 26, 2020 17:05
Show Gist options
  • Save kudaba/1da9ec16740147fd2a4045f4a72311f4 to your computer and use it in GitHub Desktop.
Save kudaba/1da9ec16740147fd2a4045f4a72311f4 to your computer and use it in GitHub Desktop.
Helper for adapting structured bindings
//-------------------------------------------------------------------------------------------------
// Leaving this here for safe keeping but not integrating into my code just yet. It basically
// requires you to upgrade to Clang 8+ and newer versions of vs 2019 to work without weird compiler bugs.
//-------------------------------------------------------------------------------------------------
#include <tuple>
//-------------------------------------------------------------------------------------------------
// Helper to simplify generating custom structured bindings
// Usage:
// STRUCTURED_BINDING(KeyValuePair, 2)
// {
// if constexpr (index == 0)
// return input.Key();
// else
// return input.Value();
// }
//-------------------------------------------------------------------------------------------------
#define STRUCTURED_BINDING(Type, Count) STRUCTURED_BINDING_V(Type, Count, input)
#define STRUCTURED_BINDING_V(Type, Count, arg) \
namespace std { \
template <> struct tuple_size<Type> { enum { value = Count }; }; \
template <size_t index> struct tuple_element<index, Type> { using type = decltype(get<index>(*((Type*)0))); }; \
} template <size_t index> auto get(Type const& arg)
//-------------------------------------------------------------------------------------------------
// Example custom iterator
//-------------------------------------------------------------------------------------------------
class Iterator
{
public:
Iterator() = default;
int const& Key() const { return k; }
int const& Value() const { return v; }
private:
int k;
int v;
};
//-------------------------------------------------------------------------------------------------
// Create binding
//-------------------------------------------------------------------------------------------------
STRUCTURED_BINDING(Iterator, 2)
{
if constexpr (index == 0)
return input.Key();
else
return input.Value();
}
//-------------------------------------------------------------------------------------------------
// Example usage
//-------------------------------------------------------------------------------------------------
int main()
{
int r = 0;
Iterator arr[10];
for (auto itr : arr)
{
auto const&[key, value] = itr;
r += key + value;
}
for (auto const&[key, value] : arr)
{
r += key + value;
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment