2011-11-03 63 views
0

我在頭文件中聲明瞭幾個小幫助函數。它看起來像這樣:混合函數模板和普通函數

//contents of foo.h 
#ifndef FOO_H 
#define FOO_H 

void foo1(int a); 
template <class mType> 
void foo2(mType b); 

#endif 

//contents of foo.cpp 
#include foo.h 

void foo1(int a) 
{ 
    ... 
} 

template <class mType> 
void foo2(mType a) 
{ 
    ... 
} 

通常只有函數模板的時候,我會在foo.h中的末尾添加#include "foo.cpp" 做出的在編譯時,編譯器看到的模板函數的實現。但是,當混合功能模板和普通功能時,這種方法似乎不起作用。在這種情況下,如何解決模板功能和普通功能?

回答

2

您不應該包含cpp文件。

將模板的實現放在頭文件中。如果你想保持它分開,然後製作2個頭文件。

//contents of foo.h 

void foo1(int a); 

template <class mType> 
void foo2(mType a) 
{ 
... 
} 

//contents of foo.cpp 
#include foo.h 

void foo1(int a) 
{ 
... 
} 

(另外,還有就是export關鍵字,雖然沒有大的編譯器都支持它,它在C++ 11換言之被刪除,請不要使用它)

+0

我都特別想downvote甚至提到沒有任何人''export''關鍵字實現的無用功能。否則,很好的答案。 –

+0

@AlexandreC。我認爲使用'export'比包含一個cpp文件要好。 – Pubby

+0

在這種情況下,我想說明一下。 –