Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overload rules for multiple, templated constructors in list initialization

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?

like image 935
MikeMB Avatar asked Nov 23 '16 14:11

MikeMB


1 Answers

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.

like image 102
sp2danny Avatar answered Oct 06 '22 00:10

sp2danny