Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

Sepples fun: Quiz questions

Name: Anonymous 2008-10-11 7:07

Q1. What is the output of the following code:
#include <list>
#include <iostream>
#include <cmath>

typedef std::pair<double, double> specimen_t;
typedef std::list<specimen_t> iteration_t;
typedef std::pair<iteration_t, iteration_t> experiment_t;

using namespace std;

double R(const specimen_t& a, const specimen_t& b)
{
    const double dx = a.first - b.first,
        dy = a.second - b.second;
    return sqrt(dx * dx + dy * dy);
}

const specimen_t globalMinimum(make_pair(9.04, 8.67));

bool inGlobalMinium(const specimen_t& s)
{
    return R(globalMinimum, s) <= .5;
}

bool inGlobalMinimum(const experiment_t& e)
{
    return R(globalMinimum, e.first.front()) <= .5;
}

int main()
{
    const specimen_t s(globalMinimum);
    cout << inGlobalMinimum(s) << endl;
    return 0;
}


Q2. Try to compile this code with all possible warnings enabled in your compiler of choice. What does it return?

Q3. Why doesn't it report any errors?

PS. This is something I've wasted a couple of hours on but finally figured out.

Name: Anonymous 2008-10-11 11:24

Apparently there is a ``copy'' constructor for pairs of completely different types.  So the compiler considers it an implicit cast, and the doubles downcast to size_type allowing it to invoke the pre-filled list constructor (also seen as a copy) for first and second, creating whatever type of list it wants.

  template<class _T1, class _T2>
    struct pair
    {
      ...
     
      /** There is also a templated copy ctor for the @c pair class itself.  */
      template<class _U1, class _U2>
        pair(const pair<_U1, _U2>& __p)
    : first(__p.first), second(__p.second) { }
    };

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List