2012-07-02 82 views
0

我一直在这个问题上一整天都陷入困境。基本上我想检查一下确认模板类型是继承自我正在做的事情的类。为了做到这一点,我使用了std :: enable_if,并且我有一些工作方式可以在编译时使用,但是当我试图实际地对类进行某些操作时,我一直在收到liker未定义的引用错误。C++模板类继承检查

class TrainingCompare 
{ 
public: 
    virtual bool operator() (PUnitType& lhs, PUnitType& rhs)=0; 
}; 

// The following Magic will result in a type error if T does not inherit from TrainingCompare 
template<class T, class Enable = void> 
class TrainAction; 

template <class T> 
class TrainAction<T, 
    typename std::enable_if< std::is_base_of< TrainingCompare, T >::value>::type> 
    : public BasicAction 
{ 
    priority_queue<UnitType, vector<PUnitType>, T> trainQueue; 
public: 
    TrainAction(); 
    void addUnitRequest(UnitType uType, int priority = 0); 
}; 

获取源文件编译是一个挑战,但我想出了看起来像废话总有很多的,所以我做了一个宏观收缩的代码。

#include "TrainAction.h" 

#define Magic(rtype) template <class T>\ 
    rtype TrainAction<T, typename std::enable_if< std::is_base_of< TrainingCompare, T >::value>::type> 

template<class T> 
TrainAction<T, typename std::enable_if< std::is_base_of< TrainingCompare, T >::value>::type>::TrainAction() 
{ 
    group = NULL; 
} 

Magic(void)::addUnitRequest(UnitType uType, int priority = 0) 
{ 
    trainQueue.push(PUnitType(UnitType)); 
} 

我有这样的感觉,我的宏是错的,但我的头是正确的,但这只是一个预感。提前致谢。

1>ExampleAIModule.obj : error LNK2001: unresolved external symbol "public: void __thiscall TrainAction<class TrainComp,void>::addUnitRequest(class BWAPI::UnitType,int)" ([email protected][email protected]@@[email protected]@[email protected]@@[email protected]) 
1>ExampleAIModule.obj : error LNK2001: unresolved external symbol "public: __thiscall TrainAction<class TrainComp,void>::TrainAction<class TrainComp,void>(void)" ([email protected]@@[email protected]@[email protected]) 
1>C:\bwapi4\broodwarbot\branches\DR_BWAIModule\Release\ExampleAIModule.dll : fatal error LNK1120: 2 unresolved externals 
+0

复制并粘贴您收到的错误。 –

+0

它的奇怪,因为我可以通过将代码放在头文件中使错误消失,但这不是一个很好的解决方案 – Daniel

+0

所有模板代码**必须在头中。这就是C++的工作方式。 –

回答

0

问题是所有的模板代码都必须在标题中。