简体   繁体   English

使用带有向量和向量函数的模板

[英]using templates with vectors and vector functions

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. Word是包含std :: string和int的结构,而data是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. 感谢您提前的时间。

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. 否则你必须明确地给它的模板参数赋予函数,因为它不能从rvalue中推导出你将返回值分配给类型应该是什么。 Not too mention passing an out paramater by reference like this saves you some performance. 不太提及通过引用传递out参数,这样可以节省一些性能。

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. 编译器无法在没有提示的情况下解析它,因为除了返回值之外的任何地方都不使用T 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. 通常,模板参数也用作模板函数的一个(或多个)参数的类型,然后编译器就能直接解析它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM