Overload rules for multiple, templated constructors in list initialization
Asked Answered
P

1

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?

Preventive answered 23/11, 2016 at 14:30 Comment(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... exampleDissemble
L
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.

Lalia answered 10/9, 2018 at 11:4 Comment(1)
Thanks. That is good to know. I 'll see if I can find the defect report when I have the time.Preventive

© 2022 - 2024 — McMap. All rights reserved.