代码之家  ›  专栏  ›  技术社区  ›  Newline

C++初始化集合为什么不能与模板结构一起工作

  •  1
  • Newline  · 技术社区  · 4 年前

    此代码可以工作,无需指定构造函数:

    struct Foo
    {
        int a;
        int b;
    };
    
    //...
    
        int a1, b1;
    
        Foo foo = {a1, b1};
    

    如果我把Foo作为模板,它就不起作用了。

    template<typename T1, typename T2>
    struct Foo
    {
        T1 a;
        T2 b;
    };
    
    //...
    
        int a1, b1;
    
        Foo foo = {a1, b1};
    

    它说扣除失败,提供了2个参数,而预期为1个。如果我添加一个构造函数,比如 Foo(T1, T2){} 然后它就起作用了。我想,这种构造在默认情况下只适用于结构。我做错了什么?

    编辑: 我使用的是Clang,它似乎不支持它。MSVC和GCC都使用c++20编译器标志编译它。

    1 回复  |  直到 4 年前
        1
  •  4
  •   songyuanyao    4 年前

    由于C++20聚合隐式生成了演绎指南,所以 class template argument deduction 也适用于骨料。

    int a1, b1;
    Foo foo = {a1, b1}; // works since C++20; T1 and T2 are deduced as int
    

    在C++20之前,您需要添加用户定义的扣减指南,例如。

    template<typename T1, typename T2>
    struct Foo
    {
        T1 a;
        T2 b;
    };
    
    template<class T1, class T2> Foo(T1 a, T2 b) -> Foo<T1, T2>;
    

    Clang 不支持 聚合的类模板参数推断 然而