2012-07-02 45 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

問題是所有的模板代碼都必須在標題中。