对模板成员函数的未定义引用
C++ undefined reference to template member function
//Forward declaration
class MyType;
class Factory{
template<class T>
static T* CreateObject(T& newOb){
return &newOb;
}
//Other non template functions
}
//In main (error causing line)
MyType tmptype;
MyType* newMyType = Factory::CreateObject<MyType>(tmptype);
这段代码导致这个错误:对' MyType* Factory::CreateObject(MyType&)'的未定义引用
我也得到这个警告:警告:没有在命令行上指定——enable-auto-import,自动导入已被激活
另外,如果我使用int类型,它仍然不能工作,这就排除了该类型没有被正确包含的可能性。
函数接受一个引用,所以你需要传递给它一个变量,编译器可能会接受这个变量的地址。
class Factory{
public:
template<class T>
static T* CreateObject(T& newOb){
return &newOb;
}
//Other non template functions
};
class MyType {};
int main() {
MyType a;
MyType* newMyType = Factory::CreateObject<MyType>(a);
}
您没有定义MyType。如果要向Factory类传递要创建的对象,则需要定义要传递的类型。没有传入对象的类型,工厂类是不可能创建对象的!所以你的MyType应该是一个原生的类型定义,或者是一个定义你自己的数据类型的结构/类。
在理想的情况下,
class MyType{
//Some data structure or type that you want to use.
};
和
class Factory{
public:
template<class T>
static T* CreateObject(T& newOb){
return &newOb;
}
//Other non template functions
}
将允许您的工厂类创建您自己类型的对象。
答案很简单。你的函数调用语法错误。你只需要调用Factory::CreateObject(tmptype);
你不需要像模板化类那样实例化一个模板化函数。
相关文章:
- 对C宏的未定义引用,但在定义它时会出现重新定义错误
- 编译时的 CImg 库返回对"__imp_SetDIBitsToDevice"的未定义引用
- 对Py_Initialize()的未定义引用
- 使用mysql c++连接器的未定义引用
- 对 Scalar ::Scalar() 的未定义引用
- 对复制 CTOR 和 CTOR 的未定义引用
- 对显式实例化的模板函数的未定义引用
- TensorRT (C++ API) 对"createNvOnnxParser_INTERNAL"的未定义引用
- 2个模板化类的非模板友元函数未定义引用错误
- 编译 libfluid 样本控制器时对"event_base_del_virtual"的未定义引用
- 获取对function_name的未定义引用
- 对 'std::thread::_M_start_thread CMake 的未定义引用进行基准测试
- 对结构方法的未定义引用
- 使用内联函数 c++ 的未定义引用
- 对 CMake 中'cudaRegisterLinkedBinary'链接错误的未定义引用?
- 对 DLOPEN 的未定义引用
- QT C++中对全局变量的未定义引用
- 快速数学导致对"__pow_finite"的未定义引用
- 对 boost::system::d etail::system_category_instance 的未定义引用,从
- OpenCV 3.4.3 中对 'cv::String::d eallocate()' 错误的未定义引用