Prunus Persica
Prunus Persica

Reputation: 1203

GTEST: False negative for incorrect number of macro arguments

I have a class A for which I've overloaded the operator[] such that if object a of class A can have an std::valarray passed to it in the following manner:

 std::valarray<int> in{2,1};
 auto b = a[in]; // lets say this returns an int k = 2
 auto c = a[{2,1}]; // also returns an int k = 2

However, when using the GTEST framework, it doesn't like the a[{2,1}] notation, and complains that macro "EXPECT_EQ" passed 3 arguments, but takes just 2 if we are to try a test such as EXPECT_EQ(2, a[{2,1}]);

Surely a[{2,1}] is a single argument, since it evaluates to an int? This doesn't seem to be the case. A typical EXPECT_EQ such as EXPECT_EQ(2, 2); is just fine.

Below, I have a MWE of a class that overloads [] to takes a parameter of type std::valarray.

class A
{
private:
    std::vector<int> elems;
public:
    A(std::vector<int> elems)
    : elems(elems){};

    int operator[](std::valarray<int> idx) const 
    {
        return get_elem(idx[0]);
    }; // getter

    int get_elem(int idx) const {return this->elems[idx];}; //getter
    int &get_elem(int idx) {return this->elems[idx];}; //setter

  }; 

int main()
{
    std::vector<int> elems = {2, 5, 0, 9,
                              5, 1, 4, 6};

    A a(elems);
    std::cout<< "hello world" << std::endl;

    std::valarray<int> in{2,1};
    auto b = a[in]; // lets say this returns an int k = 2
    auto c = a[{2,1}]; // also returns an int k = 2
    std::cout<< b << std::endl;
    std::cout<< c << std::endl;

    return 0; 
}

Given that my main() displays correct behaviour, I suspect that there is an issue with GTEST, or is evaluation order in C++ different from what I expect?

Upvotes: 1

Views: 865

Answers (1)

Since macros are involved, and there is no getting rid of them, the quickest solution is a judicious use of parentheses:

EXPECT_EQ(2, ( a[{2,1}] ));

The extra pair will prevent the comma from being interpreted as an argument separator for the macro. As for the comparison itself, a parenthesized expression has the exact same value and value-category as the expression withing the parentheses. So everything should still work1.


1 - Unless Google Test applies decltype to that second sequence of tokens, then the extra parentheses can potentially cause surprises. But it shouldn't be doing that.

Upvotes: 4

Related Questions