c++ - 统一与传统初始化产生不同的编译结果
问题描述
我在用一段微不足道的代码置换时注意到了这一点:
struct Base0 {};
struct Base1 {};
template<typename... Ts>
struct Derived: Ts... {};
int main() {
Derived<Base0, Base1> d0 {Base0{}, Base1{}}; // OK
Derived<Base0, Base1> d1 (Base0{}, Base1{}); // ERROR
}
我认为两者都d0
应该d1
导致编译错误,因为我看不出Derived
没有任何匹配的 ctor 如何将 ctor 参数作为传递并且 flagsd0
的编译很好。
我可能缺少一些明显的东西。使它通过的统一初始化是什么?是聚合初始化还是什么?传递给 ctor 的临时人员发生了什么?
编辑
如被问及,我提供了吐出的复制粘贴:
main.cpp: In function ‘int main()’:
main.cpp:9:47: error: no matching function for call to ‘Derived::Derived(Base0, Base1)’
Derived<Base0, Base1> d1 (Base0{}, Base1{}); // ERROR
^
main.cpp:5:8: note: candidate: constexpr Derived::Derived()
struct Derived: Ts... {};
^~~~~~~
main.cpp:5:8: note: candidate expects 0 arguments, 2 provided
main.cpp:5:8: note: candidate: constexpr Derived::Derived(const Derived&)
main.cpp:5:8: note: candidate expects 1 argument, 2 provided
main.cpp:5:8: note: candidate: constexpr Derived::Derived(Derived&&)
main.cpp:5:8: note: candidate expects 1 argument, 2 provided
解决方案
看起来这是聚合初始化的新 C++17 功能:
Each direct public base, (since C++17) array element, or non-static class member, in order of array subscript/appearance in the class definition, is copy-initialized from the corresponding clause of the initializer list.
It comes with the change that a class with bases may now be an aggregate (as long as they are not virtual
, private
, or protected
… though they don't even need to be aggregates! ).
Your failing case does not use aggregate initialisation, but instead attempts a good old-fashioned constructor invocation. As you've identified, no such constructor exists.
推荐阅读
- c# - 如何为我在 Visual Studio 2019 中制作的 C# 控制台应用程序(Checkers Game)创建安装程序?
- coldfusion - 当我在 CF admin 中查看时间表时,它会引发错误
- c++ - 将更多元素分配给一个 ID
- r - 系数不可估计模型.矩阵
- android - 错误出现在 firebaseRecyclerAdapter 视图适配器部分
- angular8 - 角度 8 中的 ag-grid Cell Renderer 中使用的按钮无法点击点击事件
- c++ - Convert multi-line if statment to single line with map
- performance - 提高电子邮件分类的准确性?
- r - ggplot中的R自定义调色板
- json - 如何在 Flutter 中对 JSON 数据执行文本搜索?