https://gcc.gnu.org/bugzilla/show_bug.cgi?id=102247
Bug ID: 102247
Summary: Overload resolution with brace-init is ambiguous when
it shouldn't be
Product: gcc
Version: unknown
Status: UNCONFIRMED
Severity: normal
Priority: P3
Component: c++
Assignee: unassigned at gcc dot gnu.org
Reporter: ldionne.2 at gmail dot com
Target Milestone: ---
The following code fails to compile when I believe it should succeed
(https://godbolt.org/z/z9aved8Wb):
#include <type_traits>
template <class T1, class T2>
struct pair {
template<class U1 = T1, class U2 = T2>
constexpr pair(U1&&, U2&&) { }
};
struct BraceInit { BraceInit() = default; };
struct ExplicitBraceInit { explicit ExplicitBraceInit() = default; };
constexpr int f(pair<ExplicitBraceInit, ExplicitBraceInit>) { return 1; }
constexpr int f(pair<BraceInit, BraceInit>) { return 2; }
static_assert(f({{}, {}}) == 2, "");
Indeed, the error is
<source>:15:16: error: call of overloaded 'f(<brace-enclosed initializer
list>)' is ambiguous
15 | static_assert(f({{}, {}}) == 2, "");
| ~^~~~~~~~~~
<source>:12:15: note: candidate: 'constexpr int f(pair<ExplicitBraceInit,
ExplicitBraceInit>)'
12 | constexpr int f(pair<ExplicitBraceInit, ExplicitBraceInit>) { return
1; }
| ^
<source>:13:15: note: candidate: 'constexpr int f(pair<BraceInit,
BraceInit>)'
13 | constexpr int f(pair<BraceInit, BraceInit>) { return 2; }
| ^
Compiler returned: 1
I think it should succeed because `f(pair<ExplicitBraceInit,
ExplicitBraceInit>)` can never be selected, since selecting it would require
using the explicit constructor of `ExplicitBraceInit`. And indeed, if we try to
call `f(pair<ExplicitBraceInit, ExplicitBraceInit>)` alone, we get
(https://godbolt.org/z/W33Pvnnoe):
<source>:15:16: error: converting to 'ExplicitBraceInit' from initializer
list would use explicit constructor 'constexpr
ExplicitBraceInit::ExplicitBraceInit()'
15 | static_assert(f({{}, {}}) == 2, "");
| ~^~~~~~~~~~
Compiler returned: 1
So I'm not sure why that overload is considered valid for overload resolution
(leading to the ambiguity), but it seems like GCC itself doesn't think it's
valid when there are no other candidates. Also note that Clang compiles this
code without issue, calling the non-explicit BraceInit version as expected.
This issue was uncovered while implementing http://wg21.link/P1951 in libc++.