Skip to content

Instantly share code, notes, and snippets.

@DanielUranga
Created May 7, 2017 19:39
Show Gist options
  • Save DanielUranga/28da7c632444bf65b1fa6fb43d4785b6 to your computer and use it in GitHub Desktop.
Save DanielUranga/28da7c632444bf65b1fa6fb43d4785b6 to your computer and use it in GitHub Desktop.
null created by danieluranga - https://repl.it/HkrZ/3
#include <iostream>
enum Id
{
A, B, C, D
};
struct Data
{
Id id;
const char* val;
};
constexpr Data arr[] =
{
{A, "test"},
{B, "otra cosa"},
{C, "tercera"},
};
constexpr int arrLength() { return sizeof(arr) / sizeof(arr[0]); }
template<Id id, int index>
struct findById2
{
static constexpr const Data* value = (id == arr[index].id) ? &arr[index] : findById2<id, index + 1>::value;
};
template<Id id>
struct findById2<id, arrLength()>
{
static constexpr const Data* value = id == arr[arrLength() - 1].id ? arr : nullptr;
};
template<Id id>
struct findById
{
static constexpr const Data* value = findById2<id, 0>::value;
};
int main()
{
std::cout << "A: " << findById<A>::value->val << std::endl;
std::cout << "B: " << findById<B>::value->val << std::endl;
std::cout << "C: " << findById<C>::value->val << std::endl;
static_assert(findById<C>::value != nullptr, "err");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment