Search code examples
c++c++11auto

How can I determine the actual type of an 'auto' variable


In this response:

https://stackoverflow.com/a/14382318/1676605

this program is given:

std::vector<int> vi{ 0, 2, 4 };
std::vector<std::string> vs{ "1", "3", "5", "7" };
for (auto i : redi::zip(vi, vs))
    std::cout << i.get<0>() << ' ' << i.get<1>() << ' ';

I have no idea what the type of auto i is, making it harder to reuse expertise and learn from examples. Here is what changing auto i into char i returns

In function ‘int main()’:|
/data/cbworkspace/TestZip/TestZip.cpp|14|error: cannot convert ‘boost::iterator_facade<boost::zip_iterator<boost::tuples::tuple<__gnu_cxx::__normal_iterator<int*, std::vector<int> >, __gnu_cxx::__normal_iterator<int*, std::vector<int> > > >, boost::tuples::cons<int&, boost::tuples::cons<int&, boost::tuples::null_type> >, boost::random_access_traversal_tag, boost::tuples::cons<int&, boost::tuples::cons<int&, boost::tuples::null_type> >, long int>::reference {aka boost::tuples::cons<int&, boost::tuples::cons<int&, boost::tuples::null_type> >}’ to ‘char’ in initialization|
/data/cbworkspace/TestZip/TestZip.cpp|14|warning: unused variable ‘i’ [-Wunused-variable]|
||=== Build finished: 1 errors, 1 warnings (0 minutes, 0 seconds) ===|

Try to figure out the type from that.

Is there a way to figure out what the type a variable of an auto is in C++11? To be more clear, I have a struct like this:

struct EventData
{
    // return value from redi::zip<std::vector<PriceQuote>, std::vector<PriceQuote>> what goes here????? So REDI::Zip is zipping PriceQuote, PriceQuote of bids and asks.
};

struct PriceQuote
{
   double price;
   double size;
};

Solution

  • Why do you want to put that type in a struct? It's not really designed to be used like that (I should know, I wrote it!) but if necessary you can use decltype and std::declvalto determine the type (which will still give the right answer if I change the implementation of redi::zip)

    struct EventData
    {
      // type returned by redi::zip
      typedef decltype(redi::zip(std::declval<V1>(), std::declval<V2>())) zipper_type;
    
      // type referred to by zipper_type::iterator
      typedef std::iterator_traits<zipper_type::iterator>::value_type zipped_type;
    
      zipper_type m_zipper;
    };
    

    N.B. why are you creating a typedef for the struct? This is C++ not C, stop it.

    I have no idea what the type of auto i is, making it harder to reuse expertise and learn from examples.

    Get used to it. Do you know the type that std::bind returns? Do you know the type that std::mem_fn returns? Do you know the type that a lambda expression creates? No, you don't need to know, all you need to know is what properties it has and what you can do with it, not what it's called or what types it contains.