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

C++ 使用带有向量和向量函数的模板,c++,templates,vector,C++,Templates,Vector,我正在尝试模板向量。我主要有以下几点: std::vector<Word> concordance = push_vector(data); std::向量一致性=推送向量(数据); 其中Word是包含std::string和int的结构,data是std::string。在我的头文件中,我有: template <typename T> std::vector<T> push_vector(std::string&); 模板 std::ve

我正在尝试模板向量。我主要有以下几点:

std::vector<Word> concordance = push_vector(data);
std::向量一致性=推送向量(数据);
其中Word是包含std::string和int的结构,data是std::string。在我的头文件中,我有:

 template <typename T>
 std::vector<T> push_vector(std::string&);
模板
std::vector push_vector(std::string&);
但是,当我编译时,会出现以下错误:

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&)
main.cpp:在函数“int main(int,char**)”中:
main.cpp:27:53:错误:调用“push_vector(std::string&)”时没有匹配的函数
main.cpp:27:53:注:候选人为:
templates.h:13:20:注意:模板std::vector push_vector(std::string&)
我知道我在实现模板函数时遗漏了一些东西,但我不确定是什么。提前感谢您的时间。

试试:

std::vector<Word> concordance = push_vector<Word>(data);
std::向量一致性=推送向量(数据);

编译器无法在没有提示的情况下解析它,因为除了返回值之外,您不使用
t
。通常,模板参数也被用作一个(或多个)模板函数参数的类型,然后编译器将能够直接解析它。

如果我了解您实际想要做什么,可能更像这样:

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
}
模板
void push_vector(常量std::string和str,std::vector和vec)
{
//如果可能,将str转换为T
//也许是失败吧?
//用转换后的数据分配vec
}
那么就这样称呼它:

std::string data("Hello");
std::vector<Word> concordance;
push_vector(data, concordance);
std::字符串数据(“Hello”);
向量一致性;
推送向量(数据、一致性);

否则,您必须显式地为函数指定它的模板参数,因为它无法从您将返回值赋给类型的右值中推断。更不用说像这样通过引用传递参数可以节省一些性能。

您的建议最有意义。我在代码中实现了它,它工作得非常好。非常感谢。