我正在嘗試創建一個與模板一起使用的函式,該模板應該適應具有vector默認類本身的容器。T<int>例如。但是,當我嘗試在其中使用此函式時main,出現沒有匹配函式的錯誤。
#include<string>
#include<iostream>
#include<fstream>
#include<vector>
#include<list>
#include<deque>
#include<forward_list>
using namespace std;
template<template <typename> class Container = vector>
Container<string> filter_codes(const string& route, const char& init) {
Container<string> _return;
vector<string> temp;
ifstream file(route);
string wd;
while(file>>wd){
if(wd[0]==init)
temp.push_back(wd);
}
_return.resize(temp.size());
copy(temp.begin(), temp.end(), begin(_return));
file.close();
return _return;
}
int main(){
vector<string> code = filter_codes("a.txt", 'c');
for(auto i : code) cout<<i<<' ';
return 0;
}
錯誤是
main.cpp:36:24: error: no matching function for call to 'filter_codes'
vector<string> code = filter_codes("a.txt", 'c');
^~~~~~~~~~~~
main.cpp:14:19: note: candidate template ignored: substitution failure :
template template argument has different template parameters than its
corresponding template template parameter
Container<string> filter_codes(const string& route, const char& init)
我打算通過以下陳述句使用該函式。
vector<string> t1 = filter_codes("a.txt", 'x');
auto t2 = filter_codes<list>("a.txt", 'x');
uj5u.com熱心網友回復:
您的代碼是有效的,并且由 GCC 和 MSVC 編譯。但是,Clang 錯誤意味著您使用的模板型別需要與模板模板引數*完全匹配。由于std::vector有 2 個模板引數,而您撰寫的模板模板引數只有 1 個,因此它不是完全匹配并且失敗,即使它至少是專門的并且是有效的。
* exactly規則有一個例外,它允許在模板引數串列是可變引數包時進行匹配。您可以使用此例外讓您的代碼在 Clang 上作業。只需將您的模板模板引數更改為模板引數的可變數量
template<template <typename ...> class Container = vector>
// ^^^
Container<string> filter_codes(const string& route, const char& init) {
// ...
}
這在任何地方都有效。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/312590.html
