Created
May 7, 2017 19:39
-
-
Save DanielUranga/28da7c632444bf65b1fa6fb43d4785b6 to your computer and use it in GitHub Desktop.
null created by danieluranga - https://repl.it/HkrZ/3
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 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