2013-08-02 24 views
0

我一直在C++中學習模板,他們看起來非常方便。但是,在底部http://www.cplusplus.com/doc/tutorial/templates/的大型多文件項目中使用模板時存在一些問題:「由於模板是在需要時編譯的,因此這會強制限制多文件項目:實現(定義)模板類或函數必須與其聲明位於同一個文件中。「如何正確使用跨多文件項目的模板?

所以,舉個例子,想要寫一個關於T類型名稱運行的2D Vector類模板:

template <class T> 
    class Vector { 
     T x, y; 
    public: 
     Vector(T x, T y) 
     { 
      this->x = x; 
      this->y = y; 
     } 

     void normalize() 
     { 
      T length = sqrt(x * x + y * y); 

      x = x/length; 
      y = y/length; 
     } 
    }; 

我的問題很簡單,哪裏會你把這個模板,以便多個.cpp文件訪問到它?如果你把它放在一個Math.h文件中,你保留了所有其他自定義數學相關的聲明,那麼你是否需要inline函數,因爲它們在頭文件中?

回答

2

您可以按照您的建議將它們放入Math.h文件中。只要需要,您將#include "Math.h",然後根據需要實例化模板。

您不需要內聯定義內部函數類定義,即使在.h文件中也是如此。因此,在下面的代碼,沒有明確內聯:

template <class T> 
class Vector { 
    T x, y; 
public: 
    Vector(T x, T y) 
    { 
     this->x = x; 
     this->y = y; 
    } 

    void normalize() //no need to inline (in fact, it's automatically inlined for you) 
    { 
     T length = sqrt(x * x + y * y); 

     x = x/length; 
     y = y/length; 
    } 

    T GetX(); 
}; 


template<class T> Vector<T>::GetX() { //outside class definition, also need not be inlined 
    return x; 
} 

注意:如果向量是一個非模板類的信息getX功能需要進行內聯。其中,模板類的成員函數不需要內聯。 有關更多信息,請參閱here

當然,您可以將Vector類代碼放在Vector.h文件中,並將該文件包含在Math.h中。關於內聯的相同規則適用。然後#include "Math.h"#include "Vector.h"都會讓你訪問你的Vector類模板。

相關問題