1

I am attempting to template a vector. In my main I have the following:

std::vector<Word> concordance = push_vector(data);

Where Word is a struct containing a std::string and an int, and data is a std::string. In my header file I have:

 template <typename T>
 std::vector<T> push_vector(std::string&);

However when I compile I get the following error:

main.cpp: In function ‘int main(int, char**)’:
main.cpp:27:53: error: no matching function for call to ‘push_vector(std::string&)’
main.cpp:27:53: note: candidate is:
templates.h:13:20: note: template<class T> std::vector<T> push_vector(std::string&)

I know I am missing something when I am implementing my template function, but I am not sure what. Thank you for your time in advance.

0

2 Answers 2

1

If I understand what you actually want to do perhaps something more like this:

template <typename T>
void push_vector(const std::string& str, std::vector<T>& vec)
{
   // convert str to T if possible
   // throw on failure maybe?
   // assign vec with converted data
}

Then call it like so:

std::string data("Hello");
std::vector<Word> concordance;
push_vector(data, concordance);

Otherwise you would have to explicitly give the function it's template argument as it can't deduce from the rvalue you are assigning the return value into what the type should be. Not too mention passing an out paramater by reference like this saves you some performance.

Sign up to request clarification or add additional context in comments.

1 Comment

Your suggestion makes the most sense. I implemented it in my code and it worked perfectly. Thank you.
1

Try:

std::vector<Word> concordance = push_vector<Word>(data);

The compiler can't resolve it without a hint because you don't use T anywhere other than the return value. Usually, the template parameter is also used as the type of one (or more) of the template functions' parameters, and then the compiler would be able to resolve it directly.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.