Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/xpath/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Qt中的模板类_Qt_Templates - Fatal编程技术网

Qt中的模板类

Qt中的模板类,qt,templates,Qt,Templates,是否可以使用一个不基于QObject且Qt中没有Q_OBJECT宏的模板类?在尝试使用模板化类时,我不断遇到链接器错误。但是,当我从类中删除模板时,它可以很好地编译和链接。我只是试图声明一个Filter类型的局部变量,它使用一个模板,我得到这个链接器错误: error: undefined reference to `NumericFilter<int>::NumericFilter(int, int)' 主窗口 mainwindow.cpp 过滤器.h filter.cpp 请注

是否可以使用一个不基于QObject且Qt中没有Q_OBJECT宏的模板类?在尝试使用模板化类时,我不断遇到链接器错误。但是,当我从类中删除模板时,它可以很好地编译和链接。我只是试图声明一个Filter类型的局部变量,它使用一个模板,我得到这个链接器错误:

error: undefined reference to `NumericFilter<int>::NumericFilter(int, int)'
主窗口

mainwindow.cpp

过滤器.h

filter.cpp

请注意,如果删除声明和源文件中的模板并注释掉“T”成员,则它可以正常编译

如果编译并尝试链接这两个.cpp文件,大多数编译器将生成链接器错误。有两种解决方案。第一种解决方案是将模板函数的定义物理地移动到.h文件中,即使它不是内联函数

这个解决方案可能会,也可能不会!导致代码大量膨胀,这意味着您的可执行文件大小可能会急剧增加,或者,如果您的编译器足够聪明,可能不会;试试看。 另一种解决方案是将模板函数的定义保留在.cpp文件中,只需添加行模板void foo;到该文件:

因此,对于您的案例,您的.cpp文件中有:

#include "filter.h"

template <class T>
NumericFilter<T>::NumericFilter(int, int)
{

}

template NumericFilter<int>::NumericFilter<int>(int, int); // added line!!!
塔达!没有编译错误

BTW,C++中模板的解释是最好的IMHO。


希望有帮助。

请分享源代码:是的,这应该可以。您必须错误地定义或实例化该类-共享您的代码。只需尝试仅在头文件中定义NumericFilter并删除filter.cpp.OK,在头文件中定义函数就行了,谢谢。这是非常令人失望的,尽管我不得不这样做,因为类定义相当大。请注意,这在任何方面都不是Qt特定的,而是C++通用的。谢谢,我将尝试此解决方案。
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "filter.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    NumericFilter<int> filter(0, 1);
}

MainWindow::~MainWindow()
{
    delete ui;
}
template <class T>
class NumericFilter {
  public:
    NumericFilter (int itemType, int val);

  protected:
    T m_val;
};
#include "filter.h"
template <class T>
NumericFilter<T>::NumericFilter (int, int)
{

}
// File "foo.cpp"
#include <iostream>
#include "foo.h"

template<typename T> void foo()
{
  std::cout << "Here I am!\n";
}

template void foo<int>();
#include "filter.h"

template <class T>
NumericFilter<T>::NumericFilter(int, int)
{

}

template NumericFilter<int>::NumericFilter<int>(int, int); // added line!!!