Mik*_*eMB 7 c++ templates overloading deleted-functions c++11
我不确定以下代码是否符合c ++ 11标准,并且应该在不同的实现中具有相同的行为:
#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};
}
Run Code Online (Sandbox Code Playgroud)
一般的想法是允许构造一个字符串文字和一个std::string(这里没有显示),但不是指针const char,这有点棘手(在这个问题中讨论).
较新版本的g ++(> = 6.0)和几乎所有clang ++版本(> = 3.4)似乎编译得很好,但是例如 g++-4.8 -std=c++11 main.cpp我得到以下错误:
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};
Run Code Online (Sandbox Code Playgroud)
所以我的问题是:
标准是否要求此代码具有某种行为?如果是,那么谁是对的?
将初始化器包含在{}对我有用的内容中,如下所示:
#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;
}
Run Code Online (Sandbox Code Playgroud)
我用 GCC 4.8.1 在 wandbox 上测试了它
https://wandbox.org/permlink/1TJF2NyT7mrKkqQ0
GCC在这里不一定是错误的,我依稀记得有一个关于此的缺陷报告。