7

I'm unsure if the following code is valid according to the c++11 standard and should have the same behavior across different implementations or not:

#include <cstddef>
struct Foo{
    template <std::size_t N>
    constexpr Foo( const char ( &other )[N] )       
    {}

    template <class T>
    constexpr Foo( const  T* const& other ) = delete;
};

struct Bar {
    Foo a;
    int b;
};

int main() {
    Bar bar{ "Hello",5};
}

The general Idea is to allow the construction from a string literal and a std::string (not shown here), but not from a pointer to const char, which is somewhat tricky (discussed in this question).

Newer versions of g++ (>=6.0) and almost all clang++ versions(>=3.4) seem to compile this just fine, but e.g. with g++-4.8 -std=c++11 main.cpp I get the following error:

main.cpp: In function ‘int main()’:
main.cpp:17:27: error: use of deleted function ‘constexpr Foo::Foo(const T* const&) [with T = char]’
     Bar bar{ "Hello",5};

So my question is:
Does the standard require a certain behavior for this code at all and if so, who is right?

MikeMB
  • 20,029
  • 9
  • 57
  • 102
  • 1
    I can only guess it is a compiler bug. Weird thing is that old compilers do not have problems with resolving pointers to array only with references... [example](http://melpon.org/wandbox/permlink/EdwgQP4NAko7A3jR) – W.F. Nov 23 '16 at 19:26

1 Answers1

1

Enclosing the initalizer in {} worked for me, like this:

#include <cstddef>

struct Foo {
    template<std::size_t N>
    constexpr Foo(const char (&)[N]) {}

    template<class T>
    constexpr Foo(const T* const&) = delete;
};

struct Bar {
    Foo a;
    int b;
};

int main() {
    Bar bar{ {"Hello"}, 5 };
    //       ^^^^^^^^^
    (void)bar;
}

I tested it on wandbox with GCC 4.8.1
https://wandbox.org/permlink/1TJF2NyT7mrKkqQ0

GCC is not necessarily incorrect here, I vaguely recall a defect report regarding this.

sp2danny
  • 7,488
  • 3
  • 31
  • 53
  • Thanks. That is good to know. I 'll see if I can find the defect report when I have the time. – MikeMB Sep 11 '18 at 06:50