Skip to content

Instantly share code, notes, and snippets.

@DanielUranga
Created May 7, 2017 18:48
Show Gist options
  • Save DanielUranga/23bc76e1a5d50e245b2774a4e0e324d3 to your computer and use it in GitHub Desktop.
Save DanielUranga/23bc76e1a5d50e245b2774a4e0e324d3 to your computer and use it in GitHub Desktop.
null created by danieluranga - https://repl.it/HkrZ/2
#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 findById
{
static constexpr const Data* value = (id == arr[index].id) ? &arr[index] : findById<id, index + 1>::value;
};
template<Id id>
struct findById<id, arrLength()>
{
static constexpr const Data* value = id == arr[arrLength() - 1].id ? arr : nullptr;
};
int main()
{
std::cout << "A: " << findById<A, 0>::value->val << std::endl;
std::cout << "B: " << findById<B, 0>::value->val << std::endl;
std::cout << "C: " << findById<C, 0>::value->val << std::endl;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment