C++ Templates Error: no matching function for call

2020-07-31 17:53发布

问题:

I can't manage to figure out why I get an error for the following code:

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>());
}

This is the error:

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> >&’

What am I doing wrong?

回答1:

You can't bind a temporary to a non-const reference.

Either change your signature to:

void foo(vector<T> const& v);

or don't pass a temporary:

vector<int> temp;
t.foo(temp);


回答2:

It looks like you're trying to separate your class into declarations (stuff that normally goes in .h files) and definitions (stuff that goes in .cpp files). However, due to the nature of templates it is common practice to put all the code for the class in the header. Template code cannot be pre-compiled (that is, it cannot be compiled into a shared library or DLL) because the type information changes when the code is used.

TLDR: The part where it says "// DO STUFF"... put that in the header and delete anything you may have in the corresponding .cpp.