Ile*_*ian 1 c++ templates vector
我无法弄清楚为什么我得到以下代码的错误:
template <typename T>
class Test{
void foo(vector<T>& v);
};
template <typename T>
void Test<T>::foo(vector<T>& v){
//DO STUFF
}
int main(){
Test<int> t;
t.foo(vector<int>());
}
Run Code Online (Sandbox Code Playgroud)
这是错误:
main.cpp: In function ‘int main()’:
main.cpp:21:21: error: no matching function for call to ‘Test<int>::foo(std::vector<int, std::allocator<int> >)’
main.cpp:21:21: note: candidate is:
main.cpp:14:6: note: void Test<T>::foo(std::vector<T>&) [with T = int]
main.cpp:14:6: note: no known conversion for argument 1 from ‘std::vector<int, std::allocator<int> >’ to ‘std::vector<int, std::allocator<int> >&’
Run Code Online (Sandbox Code Playgroud)
我究竟做错了什么?
您不能将临时绑定到非const引用.
将您的签名更改为:
void foo(vector<T> const& v);
Run Code Online (Sandbox Code Playgroud)
或者不通过临时的:
vector<int> temp;
t.foo(temp);
Run Code Online (Sandbox Code Playgroud)