模板成员函数的推断有关问题
模板成员函数的推断问题
a.h
-----------------------------------
class A{
int (A::*m_print)();
protected:
template<class T> void Hook(int (T::*print)());
virtual void InstallPrint() = 0;
public:
void Print();
};
------------------------------------
a.cpp
------------------------------------
template<class T> void A::Hook(int (T::*print)())
{
m_print = static_cast<int (A::*)()>(print);
}
void A::Print()
{
InstallPrint();
(this->*m_print)();
}
----------------------------------------
b.h
----------------------------------------
class B
:public A
{
protected:
virtual void InstallPrint();
void BPrint();
};
-----------------------------------------
b.cpp
-----------------------------------------
void B::InstallPrint()
{
Hook(BPrint);
}
void B::BPrint()
{
}
-----------------------------------------
main.cpp
-----------------------------------------
#include "a.h"
#include "b.h"
void main()
{
A *ptr = new B;
ptr->Print();
}
如上代码会发生连接错误
error LNK2019: 无法解析的外部符号 "protected: int __thiscall A::Hook<class B>(int (__thiscall B::*)(int,int))"
------解决方案--------------------
template <class T > void A::Hook(int (T::*print)())
{
m_print = static_cast <int (A::*)() >(print);
}
这个函数需要放在.h文件中,不能放cpp
------解决方案--------------------
搜索 模板分离编译
你用的编译器不支持
------解决方案--------------------
模版的声明和定义都要放在.h中
------解决方案--------------------
你的编译器不支持(其他编译器大多也都是不支持)模板的声明实现分离。
原因可以参考这个帖子
http://topic.****.net/u/20071006/19/7cb232c4-697d-408a-933b-a24bb4775c87.html
a.h
-----------------------------------
class A{
int (A::*m_print)();
protected:
template<class T> void Hook(int (T::*print)());
virtual void InstallPrint() = 0;
public:
void Print();
};
------------------------------------
a.cpp
------------------------------------
template<class T> void A::Hook(int (T::*print)())
{
m_print = static_cast<int (A::*)()>(print);
}
void A::Print()
{
InstallPrint();
(this->*m_print)();
}
----------------------------------------
b.h
----------------------------------------
class B
:public A
{
protected:
virtual void InstallPrint();
void BPrint();
};
-----------------------------------------
b.cpp
-----------------------------------------
void B::InstallPrint()
{
Hook(BPrint);
}
void B::BPrint()
{
}
-----------------------------------------
main.cpp
-----------------------------------------
#include "a.h"
#include "b.h"
void main()
{
A *ptr = new B;
ptr->Print();
}
如上代码会发生连接错误
error LNK2019: 无法解析的外部符号 "protected: int __thiscall A::Hook<class B>(int (__thiscall B::*)(int,int))"
------解决方案--------------------
template <class T > void A::Hook(int (T::*print)())
{
m_print = static_cast <int (A::*)() >(print);
}
这个函数需要放在.h文件中,不能放cpp
------解决方案--------------------
搜索 模板分离编译
你用的编译器不支持
------解决方案--------------------
模版的声明和定义都要放在.h中
------解决方案--------------------
你的编译器不支持(其他编译器大多也都是不支持)模板的声明实现分离。
原因可以参考这个帖子
http://topic.****.net/u/20071006/19/7cb232c4-697d-408a-933b-a24bb4775c87.html