0

Minimal example:

#include <utility>

struct A {
    A(int x) {}
};

int main() {
    int x = 3, y = 3;
    //std::pair<A, A> pa(A(3), A(3));
    //std::pair<A, A> pa(A(x), A(y));
    //std::pair<A, A> pa((A(x)), A(x));

    std::pair<A, A> pa(A(x), A(x));
}

Why does this C++ code snippet not compile? I tried various compilers on Godbolt, and the compiler errors/warnings look something like this:

<source>:10:29: error: redefinition of parameter 'x'
        std::pair<A, A> pa(A(x), A(x));
                                   ^
<source>:10:23: note: previous declaration is here
        std::pair<A, A> pa(A(x), A(x));
                             ^
<source>:10:20: warning: parentheses were disambiguated as a function declaration [-Wvexing-parse]
        std::pair<A, A> pa(A(x), A(x));

The commented out lines are examples of "fixes" to make it work as expected: I wish to create a new pair of constructed As. I can do it out of constants, but I can't do it out of variables with the same value as the constant! The parser breaks.

It's like it's interpreting that line as:

std::pair<A, A> pa(A x, A x);

, which I don't understand.

Can anyone explain what's going on here?

0 Answers0