Search code examples
c++qtqtestlib

QCompare test failure : wrong number of arguments produced by the [] operator on an unorded_map


Using c++/Qt5, I'm stuck with a QCOMPARE test on a MyMap object. This MyMap object has an attribute named "map" which is an unorded_map (vector < int,int> → QString).

Here is the test:

void TestMyMap::test(void)
{
  MyMap mymap = {
    { {{ {1,2}, {3,4} },}, QString("example1") },
    { {{ {1,2}, {3,5} },}, QString("example2") },
    { {{ {1,2}, {3,8} },}, QString("example3") },
  };

  QCOMPARE( mymap.size() , (std::size_t)3 );                   // OK
  QCOMPARE( mymap[{{ {1,2}, {3,8} }}] , QString("example3") ); // BOOM !
}

I got the following error on the last line : (my translation from the localized source message) :

error : the macro 'QCOMPARE' got 5 arguments but it takes only 2

I don't understand how mymap[{{ {1,2}, {3,8} }}] can somehow "produce" 4 arguments.

The MyMap operator[] is declared this way :

QString& operator[]( std::vector< std::pair<int, int> > key );  

QString& MyMap::operator[]( std::vector< std::pair<int, int> > key)
{
  return this->map[key];
}

The MyMap object is declared this way :

class MyMap {
    public:
        // PosRanges is a wrapper for vector < int, int >
        std::unordered_map<PosRanges, QString, PosRangesHasher> map;

    public:
        MyMap(std::initializer_list< IntegersAndAString >);
        QString& operator[]( std::vector< std::pair<int, int> > key );
        size_t  size(void);
};

Other tests on MyMap objects are ok. So, where's my error ?


Solution

  • The macro QCOMPARE is expecting two arguments separated by a comma. If an argument contains commas you have to put it into brackes ().

    Hence:

    QCOMPARE( ( mymap[{{ {1,2}, {3,8} }}] ) , QString("example3") )
              ^                           ^
    

    You might read: http://gcc.gnu.org/onlinedocs/cpp/Macro-Arguments.html