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?
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.
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