sorry didn't know how call question, hope fits...
i have function template gets argument template parameter. argument need have template parameter declares type of argument while calling function later on, omit type of argument. so, have kind of typedef (or other mechanism) rid of it.
i've seen similar mechnism other templates, e.g.
// given: rule template 3 arguments template<typename attr> using rule = rule<it, attr(), skipper>; when using std::get 1 can along without mentioning enum class directly:
std::get<static_cast<std::size_t>(enum::type1)>(tuple); here function, used access tuple enum (compare: https://stackoverflow.com/a/14835597/2524462)
template<typename enum, enum enum, class ... types> typename std::tuple_element<static_cast<std::size_t>(enum), std::tuple<types...> >::type& get(std::tuple<types...>& t) { return std::get<static_cast<std::size_t>(enum)>(t); } since used several enums, don't want hardwire enum in template did.
it called like: (1)
std::cout << get<myenum, myenum::type1>(tuple); questions:
can use typedef or similar call like:
std::cout << new_get < myenum::type1 > (tuple);since works std::get, there way have smarter template, in first place?
- the template here has tuple types last parameters. why not necessary spell them out here (1)? how compiler figure them out given parameter?
i'm using gcc 4.8.1 c++11 enabled.
i think best going able create get<>() function each enumeration. here example:
#include <tuple> #include <string> #include <iostream> typedef std::tuple<std::string,std::string> tuple1; typedef std::tuple<std::string,int> tuple2; enum class enum1 { name, address }; enum class enum2 { state, zip_code }; template <typename enum> constexpr std::size_t indexof(enum value) { return static_cast<std::size_t>(value); } template <typename enum,enum enum_value,typename tuple> constexpr auto get(const tuple &value) -> decltype(std::get<indexof(enum_value)>(value)) { return std::get<indexof(enum_value)>(value); } template <enum1 enum_value> constexpr auto get(const tuple1 &value) -> decltype(get<enum1,enum_value>(value)) { return get<enum1,enum_value>(value); } template <enum2 enum_value> constexpr auto get(const tuple2 &value) -> decltype(get<enum2,enum_value>(value)) { return get<enum2,enum_value>(value); } int main(int,char**) { tuple1 a("john","123 foo st"); tuple2 b("california",90210); std::cerr << get<enum1::name>(a) << "\n"; std::cerr << get<enum1::address>(a) << "\n"; std::cerr << get<enum2::state>(b) << "\n"; std::cerr << get<enum2::zip_code>(b) << "\n"; } it tedious, have benefit of compile-time checking enumerations compatible tuples.
Comments
Post a Comment