views:

199

answers:

3
typedef boost::shared_ptr<config_value_c> config_value_ptr;

typedef std::vector<config_value_ptr> config_value_vec;

config_value_vec config;

typeof (config.iterator ()) it = config.iterator ();

I want to extract an iterator to an array of boost pointers to class config_value_c. I know I can specify the iterator as std::vector<config_value_ptr>::iterator but I want to do this in a type-agnostic fashion so if I ever change the vector to a list I don't have to go back and update the code. Is that possible? Thanks.

I know typeof is not a real keyword, and I know of typeid but it doesn't do what I want.

+8  A: 

I think you want:

config_value_vec::iterator it = config.begin();

The next edition of the C++ standard (C++0x) will allow you to do:

auto it = config.begin();
Kim Gräsman
I was just writing this :P you hit post first I guess...
Terence Honles
Aw, sorry to steal your thunder :-)
Kim Gräsman
+1  A: 

I think you want this:

config_value_vec::iterator it = config.begin();

Avoid construction of iterator as it has undefined behavior.

If you will be writing a template method make sure you proceed with typename keyword.

template< typename Contener >
void some_function( Contener const& contener )
{
  typename Contener::iterator it = contener.begin();
   // do somethind with it
}
lionbest
+1  A: 

You could do one of four things:

1) Use the upcoming auto keyword, as already answered.

2) Give the container typedef a generic name so that you can change its type without wanting to rewrite general usages of it.

typedef std::vector<config_value_ptr> config_value_container;

config_value_container config;
config_value_container::iterator it = config.begin();

3) If you want the container typedef's name to stay specific, then you could make an iterator typedef.

typedef std::vector<config_value_ptr> config_value_vec;
typedef config_value_vec::iterator config_value_container_iterator;

config_value_vec config;
config_value_container_iterator it = config.begin();

Of course, if you start needing different types of iterators for the container (const vs non-const, backward vs forward, etc) then you may end up with several iterator typedefs.

4) Don't bother with it, because container types can have fundamental differences that you may not be able to resolve with simple typedefs. For instance, std::sort can be used with std::vector but not std::list. Depending on what your code does (or may need to do in the future), trying to keep it truly type-agnostic may take more time than it's worth. But you'll have to evaluate that yourself.

TheUndeadFish