c++ - Can a range-based for loop take a type argument? -


from can tell, range-based loops can take c-style array, object of type has member functions begin() , end() defined, or object of type type free functions begin(type) , end(type) can found adl.

is there way make loop take type argument, code compiles?

class staticvec{ //shortened implementation     static myiterator begin();     static myiterator end(); };  void foo() {     for(auto elem : staticvec){        dosomething(elem);     } } 

i omit necessity of writing staticvec::values() in loop.

as general solution can define

template< class type > struct static_collection {};  template< class type > auto begin( static_collection<type> const& )     -> decltype( type::begin() ) { return type::begin(); }   template< class type > auto end( static_collection<type> const& )     -> decltype( type::end() ) { return type::end(); } 

and can write e.g.

auto main() -> int {     for( auto elem : static_collection<static_vec>() )     {         std::cout << elem << ' ';     }     std::cout << '\n'; } 

addendum:
in practical cases suffice create instance of class holding static begin , end member functions, shown in jarod42’s , matt mcnabb’s answers (the former posted when posted above), e.g.

for( auto const& elem : staticvec() ) {     // ... } 

if instance creation can have undesirable side effects, or perhaps after future maintainance work, use general solution.

otherwise, if instance creation free, i’d go that.


Comments

Popular posts from this blog

java - Plugin org.apache.maven.plugins:maven-install-plugin:2.4 or one of its dependencies could not be resolved -

Round ImageView Android -

How can I utilize Yahoo Weather API in android -