【问题标题】:Why doesn't C++17 template class deduction work when I supply some of the template parameters? [duplicate]当我提供一些模板参数时,为什么 C++17 模板类推导不起作用? [复制]
【发布时间】:2017-12-26 17:59:54
【问题描述】:

C++17 引入了class template argument deduction。虽然大多数时候它只不过是一种语法糖,但在某些情况下它确实能起到拯救作用,尤其是在泛型代码中,例如 in this case

此功能的另一个不错的应用是std::array 的用法。确实,现在它引起的痛苦少了很多,只需比较这两个版本:

std::array arr{ 1, 2, 3, 4, 5 }; // with C++17 template argument deduction
std::array<int, 5> arr{ 1, 2, 3, 4, 5 }; // just a normal C++11 std::array

确实,一旦我决定再添加一个元素,我就可以在不明确将类型更改为 std::array&lt;int, 6&gt; 的情况下完成它。

但是,以下内容无法编译:

std::array arr{ 1, 2, 3.f, 4, 5 };

模板参数推导失败是有道理的,产生如下错误:

main.cpp:7:26: error: class template argument deduction failed:
     std::array arr{2,4.,5}; // will not compile

但是,当我尝试给出提示时,它并没有解决问题:

std::array<float> arr{ 1, 2, 3.f, 4, 5 }; // will not compile as well

现在编译器错误消息如下:

main.cpp:7:21: error: wrong number of template arguments (1, should be 2)
     std::array<float> arr{2,4.,5};
                    ^

这是为什么呢?为什么我不能只为类提供一些模板参数,但我可以为函数提供?

【问题讨论】:

    标签: c++ c++17 stdarray template-argument-deduction


    【解决方案1】:

    C++ 类模板从不支持部分推导。 recently been asked here 也有类似的问题,the accepted answer 表示部分扣除已包含在原始提案中,但未纳入标准。

    鉴于此,编译器错误看起来合乎逻辑。

    此外,这种情况在我的问题中引用的 CppReference 页面上进行了描述,in the section "Notes"

    std::tuple t(1, 2, 3);              // OK: deduction
    std::tuple<int,int,int> t(1, 2, 3); // OK: all arguments are provided
    std::tuple<int> t(1, 2, 3);         // Error: partial deduction
    

    PS无论如何,我自己注意到,尽管这方面众所周知并且我已经习惯了,新的扣除规则不知何故引起了我的困惑大脑,所以无论出于何种原因我开始潜意识地看到这样的情况,好像我在使用一个函数,期待与函数模板相同的行为,包括部分推导。

    如果你有同样的感觉,或者根本没有,我很想听听你在 cmets 中的想法。

    【讨论】:

    • 鉴于您已经找到问题的答案,为什么您觉得有必要发布一个新问题?
    • 我的目的是记录我的故事。因此,我假设支持“回答您自己的问题”复选框。至少,这是我从the explanation by Jeff Atwood 得到的印象。引用:“底线——毫不犹豫地在任何 Stack Exchange 网站上提出并回答您自己的问题”。我误解了吗?
    猜你喜欢
    • 1970-01-01
    • 2011-08-28
    • 2021-03-14
    • 2015-10-06
    • 2021-12-06
    • 2018-02-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多