列表初始化中多个模板构造函数的过载规则
Overload rules for multiple, templated constructors in list initialization
我不确定以下代码是否根据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};
}
一般的想法是允许字符串文字和 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};
所以我的问题是:
标准是否完全需要此代码的某些行为,如果是,谁是对的?
封闭了{}
中的Intorizer为我工作,例如:
#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;
}
我用GCC 4.8.1在Wandbox上测试了它
https://wandbox.org/permlink/1tjf2nyt7mrkkqq0
GCC不一定不正确,我隐约记得有关此的缺陷报告。
相关文章:
- "error: no matching function for call to"构造函数错误
- C++17复制构造函数,在std::unordereded_map上进行深度复制
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- 为什么在没有显式默认构造函数的情况下,将另一个结构封装在联合中作为成员的结构不能编译
- 为什么在C++中使用私有复制构造函数与删除复制构造函数
- 选择要调用的构造函数
- 如何委托派生类使用其父构造函数?
- c++ 17 中结构自动定义构造函数的规则是什么?
- 更改了C 17中受保护构造函数的规则
- 列表初始化中多个模板构造函数的过载规则
- 为什么在派生最多的类的初始值设定项列表中显式调用虚拟基类构造函数的规则,而较老的祖先已经拥有它?
- 我无法在不违反 c++ 扩展规则的情况下制作匹配的构造函数
- 对于默认定义的移动构造函数,noexcept的规则是什么
- 为什么存在 C++11 std::initializer_list 构造函数重载规则
- 内联构造函数和一个定义规则
- 不在异常中嵌入std::字符串的规则是否仍然适用于move构造函数
- 对于模板化的构造函数,几乎总是使用Auto规则
- 已删除的默认构造函数(和复制控件成员)缺少规则
- 逐字段构造函数生成的规则是什么?
- 复制构造函数-具有动态内存的类的C++五规则