[英]How to explicitly instantiate the template function in the template class?
bh:
#ifndef CCC
#define CCC
template<typename T>
class C
{
public: template<typename T1> void F(T1 t1);
};
#endif
b.cc:
#include "b.h"
#include <iostream>
using namespace std;
template<typename T>
template<typename T1>
void C<T>::F(T1 t1)
{
cout<<t1<<endl;
}
抄送:
#include "b.h"
int main(int argc, char* argv[])
{
C<int> c;
c.F(1.0f);
}
make.sh:
#!/bin/bash
g++ b.cc -fPIC -shared -o b.so -std=c++1y
g++ a.cc b.so -o a.out -std=c++1y
g ++輸出:
/tmp/ccYLnd28.o: In function `main':
a.cc:(.text+0x1f): undefined reference to `void C<int>::F<float>(float)'
collect2: error: ld returned 1 exit status
似乎在分別編譯a和b時,需要顯式實例化函數“ F”。 怎么樣?
我相信您有一個編碼錯誤。 模板類C中未定義T1。如果您希望返回值和參數為其他類型T1,則必須在模板規范中將其命名。 或者您只是有錯字。 以下兩個代碼中的任何一個都可以根據意圖工作
template<typename T>
class C
{
template<typename T>
T F(T t)
{
return t;
}
}
要么
template<typename T, T1>
class C
{
template<typename T, T1>
T1 F(T1 t)
{
return t;
}
}
第一個代碼段接受一個int並返回一個int。 當您傳遞浮點數時,我可以工作,因為C ++會自動將浮點數轉換為int,因此您將獲得一個int。 根據功能規范。
第二個片段采用浮點數,然后返回一個浮點數。 您必須修改main以指定第二個模板化參數
int main(int argc, char* argv[])
{
C<int, float> c;
c.F(1.0);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.