繁体   English   中英

接受模板作为函数参数

[英]Accept template as function parameter

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

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

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

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 这可能是模板推导规则的问题。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM