1. 程式人生 > >C++函式模板使用中的注意事項

C++函式模板使用中的注意事項

舉個例子:

template <typename elemType>
void display_message(const string &msg,const vector<elemType> &vec)
{
    cout<<msg;
    for (int ix=0;ix<vec.size();++ix)
    {
        elemType t=vec[ix];
        cout<<t<<' ';
    }
    cout<<endl;
}

這是一個簡單的函式模板的定義,但是如果把定義放在標頭檔案中,函式體放在.CPP中會出現什麼問題呢?

main.obj : error LNK2001: unresolved external symbol "void __cdecl display_message(class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > const &,class std::vector<int,class std::allocator<int> > const &)" (?display_
message@@YAXABV?$basic_string
@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@ABV?$vector@HV?$allocator@H@std@@@2@@Z)

好尷尬,你只能看出這是link的錯誤,但是如果你只這一個錯誤的話,或許沒問題,但是如果你對這個函式同時過載的話,也許你就不覺得這個問題那簡單了

template <typename elemType>
void display_message(const string &msg,const vector<elemType> &vec)
{
    cout<<msg;
    for
(int ix=0;ix<vec.size();++ix) { elemType t=vec[ix]; cout<<t<<' '; } cout<<endl; } void display_message(const string &msg, int size) { cerr<<msg<<size<<"\n"; }

這樣的過載從語法上來說是完全沒有問題的,然而,正確的做法是,將這兩個函式體,同時放在.h檔案中,或者,模板函式放在.h檔案中,普通的過載函式體,放在.cpp原始檔中,這樣就沒有任何問題了。