推导std :: array大小? [英] Deduce std::array size?

查看:100
本文介绍了推导std :: array大小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在以下代码中:

template<size_t N>
int b(int q, const std::array<int, N>& types)
{
    int r = q;
    for (int t : types)
    {
        r = r + t;
    }
    return r;
}

int main()
{
    b<2>(9, { 2,3 });
}

如何避免在b的调用中为N指定2?为什么不能自动推导这种类型?没有它,我得到一个错误:

How can I avoid having to specify 2 in the call to b for N? Why can't this type be automatically deduced? With out it I get the error:


'b':没有找到匹配的重载函数'int b(int,const
std :: array&)':无法推断出'N'的模板参数

'b': no matching overloaded function found 'int b(int,const std::array &)': could not deduce template argument for 'N'


推荐答案

C ++ 17 std :: array 类模板参数推导(CTAD)

C++17 std::array class template argument deduction (CTAD)

从C ++ 17开始,此新语言功能标准库现已使用,并且现在我们也可以省略模板类型这样就可以进行以下操作:

Starting with C++17, this new language feature is now used by the standard library and now allows us to omit the template types as well so that the following works:

main.cpp

#include <array>

int main() {
    std::array a{1, 2, 3};
}

而不是 std :: array< int,3> ; a {1、2、3};

经过以下测试:

g++ -ggdb3 -O0 -std=c++17 -Wall -Wextra -pedantic -o main.out main.cpp

例如,如果我们设置 -std = c ++ 14 ,它将无法编译:

If we set -std=c++14 instead for example, it fails to compile with:

error: missing template arguments before ‘a’

$ b $之前缺少模板参数b

在Ubuntu 18.04,GCC 7.5.0上进行了测试。

Tested on Ubuntu 18.04, GCC 7.5.0.

这篇关于推导std :: array大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆