C++中static函數模板該怎麼寫?

我寫了一個類A,類中有一個static函數模板。該函數模板聲明在頭文件A.h中,實現在源文件http://A.cc中。在main中調用該函數,編譯報錯,說無法解析這個靜態函數模板實例。但是如果把實現寫在頭文件里就不會報錯,運行很正常。希望大神們可以指點一二。下面附源代碼,這段源代碼分三個文件頭文件、源文件、main函數文件,代碼本身沒有實際意義,只是為了說明問題。

// A.h頭文件
#ifndef A_H_
#define A_H_

#include "iostream"
class A
{
public:
template&
static void Print();
};

#endif

// A.cc源文件
#include "A.h"

template&
void A::Print()
{
std::cout &<&< "A static" &<&< std::endl; } // 主函數 #include "A.h" #include &

using namespace std;

int main()
{
A::Print&();
return 0;
}


這個就是模板的基本問題,也就是實現和聲明到底應該怎麼放,我就放部分鏈接好了:C++ Templates Tutorial 參看 Implementing class template member functions 部分


因為c++標準里說a function template shall be defined in every translation unit in which it is implicitly instantiated. 你的main函數里調用了Print,就是instantiated了,但是從頭文件里如果只看到了聲明,沒有定義,當然就報錯了。


推薦閱讀:

TAG:C | 靜態方法 | 模板C |