gpt4 book ai didi

c++ - 使用带有 vector 和 vector 函数的模板

转载 作者:行者123 更新时间:2023-11-30 03:05:18 25 4
gpt4 key购买 nike

我正在尝试制作 vector 模板。在我的主要我有以下内容:

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

其中 Word 是一个包含 std::string 和 int 的结构,data 是一个 std::string。在我的头文件中,我有:

 template <typename T>
std::vector<T> 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&)

我知道我在实现模板函数时遗漏了一些东西,但我不确定是什么。感谢您提前抽出时间。

最佳答案

如果我理解你真正想做的事情,也许更像这样:

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
}

然后这样调用:

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

否则,您将不得不显式地为函数提供它的模板参数,因为它无法从右值 中推断出您正在将返回值分配给类型应该是什么。更不用说像这样通过引用传递输出参数可以节省一些性能。

关于c++ - 使用带有 vector 和 vector 函数的模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7812959/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com