Created
May 9, 2017 02:50
-
-
Save DanielUranga/930facd617698763db78e36c640072ef to your computer and use it in GitHub Desktop.
null created by danieluranga - https://repl.it/HkrZ/10
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"}, | |
}; | |
template<typename T, std::size_t size> | |
constexpr std::size_t GetArrLength(T(&)[size]) { return size; } | |
template<Id id> | |
class FindById | |
{ | |
private: | |
template<Id id2, int index> | |
struct FindById2 | |
{ | |
static constexpr const Data* value = (id == arr[index].id) ? &arr[index] : FindById2<id, index + 1>::value; | |
}; | |
template<Id id2> | |
struct FindById2<id2, GetArrLength(arr)> | |
{ | |
static constexpr const Data* value = id == arr[GetArrLength(arr) - 1].id ? arr : nullptr; | |
}; | |
public: | |
static constexpr const Data* value = FindById2<id, 0>::value; | |
static_assert(value != nullptr, "Value not found."); | |
}; | |
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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment