簡體   English   中英

具有void功能的模板專業化

[英]Template specialization with void function

我正在一個小程序,我創建一個2d數組。 該函數本身工作正常,但是當我想在其自己的文件中實現該函數時遇到問題。 它是這樣的:

mat.cpp:

#include <iostream>
#include <iomanip>
#include "matdyn.hpp";

int main(){
    int row, column;
    cin >> row;
    cin >> column;

    int** M1;
    double** M2;

    reserve(M1, row, column);
    reserve(M2, row, column);

    return 0;
}

matdyn.hpp

#ifndef dyn
#define dyn
template <typename T, typename S>
void reserve(S **, T, T);
#endif

matdyn.cpp:

#include "matrix_dyn.hpp"

template <typename S, typename T>
void reserve(S **&x, T row, T column){
    x = new S*[row];
    for(int i = 0; i < row; ++i) {
        x[i] = new S[column];
    }
}  

template void reserve<int, int, int>(int, int, int);
template void reserve<double, int, int>(double, int, int);

我的問題是matdyn.cpp的最后一部分。 我總是收到如下錯誤消息:

error: template-id ‘reserve<int, int, int>’ for ‘void reserve(int, int, int)’ does not match any template declaration    
template void reserve<int, int, int>(int, int, int);

我如何正確寫這最后兩行? 感謝您的任何幫助!

您的代碼有幾個問題:

您的函數reserve定義和聲明不匹配。

我相信你想寫:

template <typename T, typename S>
void reserve(S **x, T row, T column){

關於您的顯式模板函數實例化 ,應按以下步驟進行:

template void reserve<int, int>(int **, int, int);
template void reserve<int, double>(double **, int, int);

您必須匹配函數聲明中提供的模板參數。

這里是編譯的實時代碼

您必須將模板函數的定義放在標頭matdyn.hpp中

#ifndef dyn
#define dyn
template <typename S, typename T>
void reserve(S **&x, T row, T column){
    x = new S*[row];
    for(int i = 0; i < row; ++i) {
        x[i] = new S[column];
    }
}  

template void reserve<int, int>(int**&, int, int);
                      ^^^^^^^^  ^^^^^^
template void reserve<double, int>(double**&, int, int);
                      ^^^^^^^^^^^  ^^^^^^^^^

#endif

或將matdyn.cpp包含在matdyn.hpp中

#ifndef dyn
#define dyn
template <typename T, typename S>
void reserve(S **, T, T);

#include "matdyn.cpp"

#endif

至於原因看這個SO問題

還要注意模板專業化的錯誤。 功能模板專業化的模板參數列表必須與功能模板的模板參數列表匹配。

這里引用:

模板的定義必須在隱式實例化時可見,這就是為什么模板庫通常在標頭中提供所有模板定義的原因(例如,大多數boost庫僅是標頭)

因此,您應該將所有內容都放在頭文件中,因為這是最常見的方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM