我在整理一个简单的代码时就注意到了这一点:
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
都应该导致编译错误,因为我看不到没有任何匹配的ctor的Derived
如何将ctor参数作为传递的参数,并将d0
的编译标记为正常。我可能想念一些明显的东西。使它通过的统一初始化是什么?它是聚合初始化还是什么?传递给ctor的临时人员会怎样?
Using C++17 online compiler here
编辑
根据要求,我提供了喷出的副本粘贴:
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
最佳答案
看起来这是aggregate initialisation的C++ 17新功能:
随之而来的变化是,具有基数的类现在可以是聚合的(只要它们不是virtual
,private
或protected
…即可,尽管它们甚至不必是聚合的!😲)。
失败的案例不使用聚合初始化,而是尝试良好的老式构造函数调用。如您所知,不存在这样的构造函数。