C++模版函數聲明和定義分離導致的錯誤

最近看算法書,想寫一些通用的函數實現那些基本的算法,結果第一個就出問題了,如題目說的,C++中把模版函數的聲明和定義分別寫在了.h和.cpp文件中,導致編譯出錯。具體是這樣的:

BasicAlgorithms.h文件:

#ifndef BASIC_ALGORITHMS_H
#define BASIC_ALGORITHMS_H
#include "stdafx.h"
#include <vector>
using namespace std;

class BasicAlgorithms
{
public:
    template<typename Type> void InsertionSort(vector<Type> &);
};
#endif

然後在BasicAlgorithms.cpp文件中實現了InsertionSort()函數:

#include "stdafx.h"
#include "BasicAlgorithms.h"

template <typename Type>
void BasicAlgorithms::InsertionSort(vector<Type> &vec_to_sort)
{
    vector<Type>::size_type i=0;
    for(vector<Type::size_type j=2;j<vec_to_sort.size();j++)
    {
        Type key=vec_to_sort[j];
        i=j-1;
        while(i>0&&vec_to_sort[i]>key)
        {
            vec_to_sort[i+1]=vec_to_sort[i];
            i--;
        }
        vec_to_sort[i+1]=key;
    }
}

然後進行編譯,出現了一個錯誤:

error LNK2019: 無法解析的外部符號 "public: void __thiscall BasicAlgorithms::InsertionSort<int>(class std::vector<int,class std::allocator<int> > &)" (??$InsertionSort@H@BasicAlgorithms@@QAEXAAV?$vector@HV?$allocator@H@std@@@std@@@Z),該符號在函數 _wmain 中被引用。

按照平時的寫法習慣,就是這樣寫的,在.h文件中聲明,在.cpp文件中定義,糾結好久不知道怎麼解決,最後求助論壇,得到了結果(論壇帖子):模版不支持分離編譯,聲明和定義不能分開,都應該寫在.h文件中。修改重新寫,順利通過編譯:

BasicAlgorithms.h文件:

#ifndef BASIC_ALGORITHMS_H
#define BASIC_ALGORITHMS_H
#include "stdafx.h"
#include <vector>
using namespace std;

class BasicAlgorithms
{
public:
    template<typename Type> void InsertionSort(vector<Type> &);
};
#include "BasicAlgorithmsImplement.h"
#endif

刪除原來的BasicAlgorithms.cpp文件,增加了一個BasicAlgorithmsImplement.h,這個頭文件其實和刪除的BasicAlgorithms.pp內容一樣,是定義BasicAlgorithms.h中的模版函數:

template <typename Type>
void BasicAlgorithms::InsertionSort(vector<Type> &vec_to_sort)
{
    vector<Type>::size_type i=0;
    for(vector<Type::size_type j=2;j<vec_to_sort.size();j++)
    {
        Type key=vec_to_sort[j];
        i=j-1;
        while(i>0&&vec_to_sort[i]>key)
        {
            vec_to_sort[i+1]=vec_to_sort[i];
            i--;
        }
        vec_to_sort[i+1]=key;
    }
}

爲什麼C++中模版聲明和定義不能分開呢?搜了一下,網上也有解釋,http://blog.csdn.net/bichenggui/article/details/4207084


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章