接受模板作为功能参数

时间:2020-01-30 02:51:48

标签: c++ templates

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

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

在两种情况下,我都应该以函数内部的模板数组结尾,但只能编译一个。

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’

1 个答案:

答案 0 :(得分:1)

std::array大小的模板参数的类型为std::size_t。但是,这里您需要在函数定义中为int提供DIM。这可能是模板推导规则的问题。