Created
May 7, 2017 18:48
-
-
Save DanielUranga/23bc76e1a5d50e245b2774a4e0e324d3 to your computer and use it in GitHub Desktop.
null created by danieluranga - https://repl.it/HkrZ/2
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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