This is a simplified version which illustrate the problem:
struct Foo {
Foo() = default;
template <std::size_t N>
Foo(const char(&)[N]) {}
};
template <std::size_t N>
auto foo(const char (&arr)[N]) -> Foo
{
return arr;
}
auto main() -> int
{
foo("Stack Overflow");
}
g++ seems to decay arr
to const char *
, although an array reference argument is passed to an array reference parameter . It gives this error:
In instantiation of
Foo foo(const char (&)[N]) [with long unsigned int N = 4ul]
:error: could not convert
(const char*)arr
fromconst char*
toFoo
return arr; ^
While clang++ behaves how I expect and compiles the code.
The code compiles fine on gcc with any of those modifications:
return {arr};
return Foo(arr);
return (Foo)arr;
return static_cast<Foo>(arr);
Is it a gcc bug?
Tried it with all g++ and clang++ versions which support c++14
.(*)
(*) I just tried it with a snapshot of gcc 6
and it compiles OK. So it does look like a bug fixed in gcc 6
Yes, this was a bug in GCC where arrays would decay into pointers prematurely and the converting constructor would no longer appear to be a viable candidate. Examples similar to yours (and the eventual fix) can be found in the comments of these two bug reports:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With