显式实例化声明

时间:2015-10-13 05:06:34

标签: c++ templates

编辑我的问题请帮助:

需要一些帮助。 我使用STL矢量,我有这些文件: vectorAux.h,vectorDriver.cpp和vectorAux.cpp

我想链接这个并编译它。我最初询问明确的实例化,但我意识到这条路线不是我想要的方式。我只是希望它能帮助我解决编译问题。

我这样做是为了完成家庭作业,并按照它所说的方向去做#inc; #include vectorAux.cpp"在这个头文件的底部:

#include <iostream>
using namespace std;


#ifndef VECTORAUX_H
#define VECTORAUX_H

template<typename T>
void writeVector(const vector<T>&vect);

template<typename T>
int seqVectSearch(const vector<T>&vect, int first, int last, const T&target);

template<typename T>
void removeDup(vector<T>&vect);

#endif

长话短说,我无法完成这项工作,所以我试着看一下我曾经做过的旧项目。真正的问题是我不了解如何链接模板,我意识到你可以在头文件中包含实现,但我的老师根本不喜欢这样。

他们更喜欢我分开的东西和/或包含cpp文件......

我真的很困惑......去年我问了一个非常相似的问题,几个小时后终于成功编译了,但回答我问题的用户告诉我弄清楚为什么编译,但当然我还是不明白,因为我再次遇到这个问题......

所以我的问题很简单,我如何修复我的代码来编译?

我删除了实例化文件,因为你说我无法显式实例化函数,但我的驱动程序中仍然出现此错误:

http://prntscr.com/8qq397/direct

这是我用来声明它的代码,但它找不到与参数列表匹配的任何内容:

/*
vectorAux.cpp
Implementations of Template Functions

COSC220   Lab 7
*/

#include "vectorAux.h"
#include <vector>
#include <algorithm>
#include <iostream>

template <typename T>
void removeDup(std::vector<T> & v)
{
}


template <typename T>
unsigned seqVectSearch(const std::vector<T> & v, unsigned first, unsigned last, const T& target){
// Complete the code, use sequential search for arrays as model
return last; // if not found, return last
}

template <typename T>
void writeVector(const std::vector<T> & v){
    unsigned i;
    unsigned n = v.size();

    for (i = 0; i < n; i++)
        std::cout << v[i] << ' ';
        std::cout << std::endl;
}

这是我的司机:

#include "vectorAux.h"
#include <vector>
#include <iostream>

// fill vector with values
void fillVector(std::vector<int> & vect);

int main()
{
using namespace std;

// Declare an empty vector of int
vector<int> vect;

// Test removeDuplicate
// Fill vector with vals, write it to console
fillVector(vect);
cout << "Testing removeDup" << endl;
cout << "Original vector is  ";
writeVector(vect);

// Remove the duplicates, write it to console again
removeDup(vect);
cout << "Vector with duplicates removed is  ";
writeVector(vect);
cout << endl;
writeVector(vect);
return 0;
}

void fillVector(std::vector<int> & vect){
int arr[] = {1,7,2,7,9,1,2,8,9};
unsigned arrsize = sizeof(arr)/sizeof(int);
vect = std::vector<int>(arr, arr+arrsize);
}

1 个答案:

答案 0 :(得分:0)

您无法对函数进行显式实例化,函数不作为对象存在。但是,您可以专门化模板化函数:

template<>
void writeVector(const vector<int>&vect);

以上声明了writeVector int函数的特化。然后可以像任何其他函数一样在源文件中实现它。 (注意,你实际上不必声明上面的函数原型,模板化原型就足够了,只需实现(定义)函数。)