vendredi 25 septembre 2015

C++ pretty-printing tuples

I'm having some trouble understanding the compiler error behind this.

Let's say we have a simple program that collects three integers in a tuple and prints the tuple:

#include <iostream>
#include <tuple>

using namespace std;

typedef tuple<int,int,int> int3;

void pretty_int3(const int3& i);

int main(int argc, char *argv[]){
  ios_base::sync_with_stdio(false);

  int3 v = int3(7,8,9);

  pretty_int3(v);

  return 0;
}

Now if I choose to implement pretty_int3 like this, everything works fine:

void pretty_int3(const int3& i){
    cout << "{";
    cout << get<0>(i) << ",";
    cout << get<1>(i) << ",";
    cout << get<2>(i);
    cout << "}" << "\n";
}

No surprises there. However, when I do this, instead ...

void pretty_int3(const int3& i){
    cout.sync_with_stdio(true);
    printf("{%d,%d,%d}\n",get<0>(i),get<1>(i),get<2>(i));
    cout.sync_with_stdio(false);
}

This fails to compile:

In file included from test.cpp:2:0:

/usr/include/c++/4.8/tuple: In instantiation of ‘struct std::tuple_element<1u, std::tuple >’:

/usr/include/c++/4.8/tuple:682:12: recursively required from ‘struct std::tuple_element<2u, std::tuple >’

/usr/include/c++/4.8/tuple:682:12: required from ‘struct std::tuple_element<3u, std::tuple >’

/usr/include/c++/4.8/tuple:773:5: required by substitution of ‘template constexpr typename std::__add_r_ref >::type>::type std::get(std::tuple<_Elements ...>&&) [with unsigned int __i = 3u; _Elements = {int, int, int}]’

...

And I sure don't understand this error.

What is this telling me and why, and how do I resolve the issue?

Aucun commentaire:

Enregistrer un commentaire