Last active
August 29, 2015 14:11
-
-
Save AzothAmmo/4e9d145e5cce0a174b36 to your computer and use it in GitHub Desktop.
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> | |
namespace detail | |
{ | |
//! Creates a c string from a sequence of characters | |
/*! The c string created will always be prefixed by "tuple_element" | |
Based on code from: http://stackoverflow.com/a/20973438/710791 */ | |
template<char...Cs> struct char_seq_to_c_str | |
{ | |
static const int length = 13; // number of chars in the word: tuple_element | |
typedef const char (&arr_type)[sizeof...(Cs) + length + 1]; | |
static const char str[sizeof...(Cs) + length + 1]; | |
}; | |
template<char...Cs> | |
const char char_seq_to_c_str<Cs...>::str[sizeof...(Cs) + length + 1] = {'t','u','p','l','e','_','e','l','e','m','e','n','t', Cs..., '\0'}; | |
//! Converts a number into a sequence of characters | |
/*! @tparam Q The quotient of dividing the original number by 10 | |
@tparam R The remainder of dividing the original number by 10 | |
@tparam C The sequence built so far */ | |
template <size_t Q, size_t R, char ... C> | |
struct to_string_impl | |
{ | |
using type = typename to_string_impl<Q/10, Q%10, R+48, C...>::type; | |
}; | |
//! Base case with no quotient | |
template <size_t R, char ... C> | |
struct to_string_impl<0, R, C...> | |
{ | |
using type = char_seq_to_c_str<R+48, C...>; | |
}; | |
} | |
//! Generates a c string for a given index of a tuple | |
/*! Example use: | |
@begincode | |
tuple_element_name<3>::c_str(); // returns "tuple_element3" | |
@endcode */ | |
template <size_t T> | |
struct tuple_element_name | |
{ | |
using type = typename detail::to_string_impl<T/10, T%10>::type; | |
static const typename type::arr_type c_str() { return type::str; }; | |
}; | |
template <size_t T> | |
void example() | |
{ | |
const char* s = tuple_element_name<T>::c_str(); | |
std::cout << s << std::endl; | |
} | |
int main() | |
{ | |
example<0>(); | |
example<1>(); | |
example<2>(); | |
example<93>(); | |
example<29384>(); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Output for this example: