无法在类中使用带有数组的函数模板作为参数

时间:2022-08-14 18:52:40

I created a function template. It works fine if I use it in functions. Now, I'd like to use it inside a class but can't make the code compile:

我创建了一个功能模板。如果我在函数中使用它,它工作正常。现在,我想在类中使用它但不能使代码编译:

#include <QList>

// Function template
template <typename T>
void Array2QList(QList<T> &outList, const T in[], int &insize)
{
    for (int i = 0; i < insize; ++i)
        outList.append(in[i]);
}

// Class using the template    
class Parser
{
public:
    Parser(const unsigned char buffer[], const int numBytes){
        Array2QList<>(frame, buffer, numBytes); // This one fails
    }
    ~Parser(){}
    QList<unsigned char> frame;
};

// Main
int main(int argc, char *argv[])
{
    int size = 50;
    unsigned char buffer[size];

    QList<unsigned char> frame;

    Array2QList<unsigned char>(frame, buffer, size); // This one works

    Parser parser = Parser(buffer, size);
    return 0;
}

The error I get is:

我得到的错误是:

..\SandBox\main.cpp: In constructor 'Parser::Parser(const unsigned char*, int)':

.. \ SandBox \ main.cpp:在构造函数'Parser :: Parser(const unsigned char *,int)'中:

..\SandBox\main.cpp:20: error: no matching function for call to 'Array2QList(QList&, const unsigned char*&, const int&)'

.. \ SandBox \ main.cpp:20:错误:没有匹配函数来调用'Array2QList(QList&,const unsigned char *&,const int&)'

Note: I must arrays since it is an interface for a USB driver.

注意:我必须是数组,因为它是USB驱动程序的接口。

1 个解决方案

#1


Array2QList<>(frame, buffer, numBytes);

Here, numBytes is a const int, but Array2QList takes an int&. You can't bind a non-const reference to something that's const. It's unclear why you are taking that parameter by reference, so if you just pass by value instead, it'll work.

这里,numBytes是一个const int,但是Array2QList是一个int&。您不能将非const引用绑定到const的某些内容。目前还不清楚为什么你通过引用获取该参数,所以如果你只是通过值传递,它就会起作用。

template <typename T>
void Array2QList(QList<T> &outList, const T in[], int insize){
//                                     get rid of &  ^

#1


Array2QList<>(frame, buffer, numBytes);

Here, numBytes is a const int, but Array2QList takes an int&. You can't bind a non-const reference to something that's const. It's unclear why you are taking that parameter by reference, so if you just pass by value instead, it'll work.

这里,numBytes是一个const int,但是Array2QList是一个int&。您不能将非const引用绑定到const的某些内容。目前还不清楚为什么你通过引用获取该参数,所以如果你只是通过值传递,它就会起作用。

template <typename T>
void Array2QList(QList<T> &outList, const T in[], int insize){
//                                     get rid of &  ^