[問題] C++ template 宣告和函數分開寫
開發平台(Platform): (Ex: VC++, GCC, Linux, ...)
g++ linux
額外使用到的函數庫(Library Used): (Ex: OpenGL, ...)
問題(Question) *[m
在myprint.hpp裡面宣告函數型態 template <class T> myprint...,
在myprint.cpp裡面定義函數,
test_mypint.cpp裡面用main呼叫myprit,
compile時找不到函數。
餵入的資料(Input):
沒有
預期的正確結果(Expected Output):
錯誤結果(Wrong Output):
/tmp/cc3Zk2SY.o: In function `main':
test_myprint.cpp:(.text+0x63): undefined reference to `void myprint<double>(double*, int, char*)'
collect2: ld returned 1 exit status
程式碼(Code):(請善用置底文網頁, 記得排版)
=================myprint.hpp==========================
template <class T>
void myprint(T *b, int n , char file_name[]);
======================================================
=================myprint.cpp==========================
#include <iostream>
#include <fstream>
#include <cassert>
#include "myprint.hpp"
using namespace std;
template <class T>
void myprint(T *b, int n , char file_name[]){
int i ;
ofstream myfile;
myfile.open (file_name);
assert(myfile.is_open());
for (i =0 ;i<n;i++)
myfile << b[i] << endl;
myfile.close();
return ;
}
=======================================================
==================main.cpp=============================
#include <cstdlib>
#include "myprint.hpp"
int main(){
char my_name [80] = "test_print_name.txt";
double *b = (double*)malloc(sizeof(double)*10);
myprint<double>(b, 10 , my_name);
free(b);
return 0;
}
========================================================
===============command =================================
g++ myprint.cpp test_myprint.cpp
========================================================
補充說明(Supplement):
我找到的資料是有說template不能分開寫,但是我不太懂是指什麼不能分開寫。
謝謝大家。
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 140.112.51.116
※ 編輯: hjmeric 來自: 140.112.51.116 (05/16 21:47)
→
05/16 21:48, , 1F
05/16 21:48, 1F
→
05/16 21:48, , 2F
05/16 21:48, 2F
→
05/16 21:49, , 3F
05/16 21:49, 3F
→
05/16 21:57, , 4F
05/16 21:57, 4F
→
05/16 21:58, , 5F
05/16 21:58, 5F
→
05/16 22:04, , 6F
05/16 22:04, 6F
→
05/16 22:08, , 7F
05/16 22:08, 7F
→
05/17 00:36, , 8F
05/17 00:36, 8F
→
05/17 00:37, , 9F
05/17 00:37, 9F
→
05/17 00:38, , 10F
05/17 00:38, 10F
→
05/17 00:38, , 11F
05/17 00:38, 11F
→
05/17 00:39, , 12F
05/17 00:39, 12F
→
05/17 00:41, , 13F
05/17 00:41, 13F
→
05/17 00:42, , 14F
05/17 00:42, 14F
→
05/17 00:43, , 15F
05/17 00:43, 15F
→
05/17 00:44, , 16F
05/17 00:44, 16F
→
05/17 00:44, , 17F
05/17 00:44, 17F
→
05/17 00:46, , 18F
05/17 00:46, 18F
→
05/17 01:00, , 19F
05/17 01:00, 19F
推
05/17 01:48, , 20F
05/17 01:48, 20F
→
05/17 08:24, , 21F
05/17 08:24, 21F
→
05/17 13:09, , 22F
05/17 13:09, 22F
→
05/17 17:50, , 23F
05/17 17:50, 23F