[英]LNK2019 with Template
因此,我在鏈接方面遇到了問題。 答案可能很簡單,但是我想我很傻。 我定義了一個用於計算采用stringstream的事物的類。
頭文件的相關部分:
#include <sstream>
using namespace std;
template<class T>
class Finder {
public:
Finder(istringstream& input) {};
~Finder() {};
template<typename T> Finder(T& input) {};
template<typename T> ~Finder() {};
T check(istringstream&);
template<typename T> friend ostream& operator << (ostream&, Finder<t>&);
};
template<class T>
T Finder<T>::check(istringstream& input)
然后我的驅動程序文件到最后一次調用:
#include <sstream>
#include <string>
#include <iostream>
#include "Finder.h"
using namespace std;
int main(int argc, char** argv) {
Finder<int> thing;
string expression;
getline(cin, expression);
while(expression[0] != 'q') {
try {
int result = thing.check(istringstream(expression));
錯誤為:1> driver.obj:錯誤LNK2019:未解析的外部符號“ public:__ thiscall Finder :: Finder(void)”(?? 0?$ Finder @ H @@ QAE @ XZ)在函數_main中引用
1> driver.obj:錯誤LNK2019:未解析的外部符號“公共:__ thiscall Finder ::〜Finder(void)”(?? 1?$ Finder @ H @@ QAE @ XZ)在函數__catch $ _main $ 0中引用
首先,不要只將輸入限制為字符串流。 除非您有確鑿的理由否則,請改用通用的std::istream
。 您的類將更加健壯,並能夠從多種源流類型獲取輸入,而不僅僅是std::istringstream
(例如文件流或輸入控制台)。
其次,我幾乎可以肯定這是你想要做什么:
#include <iostream>
// forward declare class
template<class T>
class Finder;
// forward declare ostream inserter
template<class T>
std::ostream& operator <<(std::ostream&, const Finder<T>&);
// full class decl
template<class T>
class Finder
{
// friend only the inserter that matches this type, as opposed to
// all inserters matching all T for Finder
friend std::ostream& operator<< <>(std::ostream&, const Finder<T>&)
{
// TODO: implement inserter code here
}
public:
Finder()
{
// TODO: default initialization here
};
Finder(const T& value)
{
// TODO: initialize directly from T value here.
}
Finder(std::istream& input)
{
// TODO: initialize from input stream here.
}
~Finder()
{
// TODO: either implement this or remove it outright. so far
// there is no evidence it is even needed.
}
T check(std::istream& input)
{
// TODO: implement check code here. currently just returning a
// value-initialized T. you will change it as-needed
return T();
};
};
用法示例為:
int main()
{
Finder<int> f;
std::istringstream iss("1 2 3");
f.check(iss);
}
注意,有一個 T
, 一個 T
來自類模板本身。 如果需要成員函數(甚至是構造函數)的輔助類型,也可以使用具有不同類型名稱的模板成員函數來完成,例如:
template<class T>
class Simple
{
public:
// a template member constructor
template<typename U>
Simple(const U& val)
{
}
// a regular template member
template<typename U>
void func(U value)
{
}
};
並這樣調用:
Simple<int> simple(3.1415926); // U will be type double
simple.func("test"); // U will be type const (&char)[5]
請注意,對於成員函數模板,就像所有函數模板一樣,類型是根據傳遞的參數推導出的,未指定(盡管它們可能是強制使用特定類型,但此處未作說明)。
無論如何,希望能有所幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.