jeudi 1 octobre 2015

What's the C++98 equivalent of the auto iterator reference?

My development environment has RHEL 5.8 which does not support GCC 4.8+ modern (C++11+) compilers. I anticipate that someday we'll get there, so I have a header file where I define macros based on C++11 support levels so I can do something like this:

#if defined(CPP11_auto_type_inference) && defined(CPP11_range_based_for_loops)
  for (auto vit : args)
#else
  std::vector<std::string>::const_iterator vit, vend;
  for (vend=args.end(),vit=args.begin(); vit != vend; ++vit)
#endif
  { // process arguments...
    std::cout << "Processing \"" << *vit << '"' << std::endl;
    . . .
  } // end "process arguments" loop

So, what I'm trying to do in C++98 is the equivalent of the iterator reference (or is it more accurate to say "a dereferenced iterator"?), like below:

for (auto& it : args)
  std::cout << "Processing \"" << it << '"' << std::endl;

For the life of me, I cannot figure out how to get a dereferenced iterator (or iterator reference) in C++98. I can simulate, as below:

#if defined(CPP11_auto_type_inference) && defined(CPP11_range_based_for_loops)
  for (auto& it : args) {
#else
  std::vector<std::string>::const_iterator vit, vend;
  for (vend=args.end(),vit=args.begin(); vit != vend; ++vit) {
    std::string it(*vit);
#endif
    std::cout << "Processing \"" << it << '"' << std::endl;
    . . .
  }

... but I'm really hoping that is not the answer.

What is the C++98 equivalent of for (auto& it : vec), or is it not possible? Is it only possible to "simulate" it but dereferencing the iterator and creating a copy each iteration?

And if that be the case, is that what is going on "under the covers" with C++11 auto& syntax? (I have to believe this is not the case.) In any case, is it more costly to use for (auto& it : vec) than for (auto it : vec)?

Thank you in advance for your insight.

Aucun commentaire:

Enregistrer un commentaire