简体   繁体   English

接受模板作为函数参数

[英]Accept template as function parameter

Could someone explain the difference between the two function calls here?有人可以在这里解释两个函数调用之间的区别吗?

When can you pass a templated variable to a function?什么时候可以将模板变量传递给函数?

In both cases I should end up with an templated array inside the function, but only one compiles.在这两种情况下,我都应该在函数内部得到一个模板化数组,但只有一个可以编译。

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;
}

EDIT: Error messages look like this:编辑:错误消息如下所示:

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’

The template parameter for the size of a std::array is of type std::size_t . std::array大小的模板参数是std::size_t类型。 However, here you require supplying an int for DIM in the function definition.但是,在这里您需要在函数定义中为DIM提供一个int This is probably an issue for the template deduction rules.这可能是模板推导规则的问题。

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

相关问题 模板可以接受函数指针或Functor的参数 - Template Parameter that can accept function pointer or Functor 让函数指针模板参数接受右值引用是否合法? - Is it legal to have a function pointer template parameter accept an rvalue reference? 是否可以使用参数包来允许模板函数接受等效类型? - Is it possible to use parameter pack to allow template function to accept equivalent types? 为什么std :: function不能接受推导类型作为模板参数? - Why can std::function not accept a deduced type as its template parameter? C ++ - 模板函数接受绑定函数作为参数并将其传递给另一个函数 - C++ - Template function to accept bound function as parameter and pass it to another function 让需要单个模板参数的模板模板参数的类接受可变参数模板参数的模板模板参数? - Make class expecting a template template parameter of single template parameter accept a template template parameter of variadic template parameter? 功能上的模板模板参数 - Template template parameter on function 具有模板参数的模板功能 - Template function with template parameter 重载operator &lt;&lt;以接受模板函数 - Overloading operator<< to accept a template function 是否可以重载函数以接受带有非类型模板参数的所有实例 - is it possible to overload a function to accept all instances of with a non-type template parameter
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM