模板参数扣除的奇怪行为

strange behavior of template argument deduction

本文关键字:参数      更新时间:2023-10-16

以下可以在C 17

下进行编译
template<class... Ts>
struct Test : Ts...
{
    using Ts::operator()...;
};
template<class... Ts> Test(Ts...) -> Test<Ts...>;

int main() {
    Test test
    {
        [](const int& i) {  },
        [](const float& f) {  }
    };
}

但是,如果我将其更改为:

    Test test
    ( //{  is changed to (
        [](const int& i) {  },
        [](const float& f) {  }
    );//}  is changed to )

它不会编译,因为测试没有使用2个参数的构造函数。我想知道为什么原始代码有效?

,因为汇总初始化在C 17中变得怪异。基本上,如果您将一个或多个公共基础类的类汇总化一类,则使用初始化器列表的第一元素来初始化基础类。在这种情况下,按照模板参数扣除,可以使用其默认的复制构造函数从lambda参数中正确初始化基类。