接受模板作为函数参数

Accept template as function parameter

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

有人可以在这里解释一下这两个函数调用之间的区别吗?

什么时候可以将模板化变量传递给函数?

在这两种情况下,我都应该在函数中得到一个模板化数组,但只有一个编译。

template<int DIM>
struct MyStruct
{
array<int, DIM> structArr;
};
template<int DIM> void testA( MyStruct  <DIM>& myStruct)    {    }
template<int DIM> void testB( array<int, DIM>& arrA)        {    }
int main()
{
MyStruct<3>     myStruct;
array<int, 3>   arr;
testA(myStruct);
testB(arr);         //compile error
return 0;
}

编辑: 错误消息如下所示:

error: no matching function for call to ‘testB(std::array&)’
testB(arr);         //compile error
^
note: candidate: template void testB(std::array&)
template<int DIM> void testB( array<int, DIM>& arrA)        {    }
^~~~~
note:   template argument deduction/substitution failed:
note:   mismatched types ‘int’ and ‘long unsigned int’

std::array大小的模板参数的类型为std::size_t。但是,此处需要为函数定义中的DIM提供int。这可能是模板扣除规则的问题。