【发布时间】:2010-12-11 00:29:33
【问题描述】:
我对 C++ 模板的情况知之甚少,但我正在尝试实现一个函数,该函数在向量中搜索满足给定属性的元素(在这种情况下,搜索具有给定名称的元素)。我在 .h 文件中的声明如下:
template <typename T>
T* find_name(std::vector<T*> v, std::string name);
编译时,调用函数时出现此链接器错误:
Error 1 error LNK2019: unresolved external symbol "class Item * __cdecl find_name<class Item>(class std::vector<class Item *,class std::allocator<class Item *> >,class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >)" (??$find_name@VItem@@@@YAPAVItem@@V?$vector@PAVItem@@V?$allocator@PAVItem@@@std@@@std@@V?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@2@@Z) referenced in function "public: class Item * __thiscall Place::get_item(class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >)" (?get_item@Place@@QAEPAVItem@@V?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@@Z) place.obj Program2
再说一次,我是模板新手,所以我不知道发生了什么。我通过 Google 找到的所有 LNK2019 实例都是关于没有使用正确的库,但由于这是我自己的函数,我不明白为什么会发生这种情况。
还有一个相关的问题:有没有办法让模板参数成为某个类的子类,即模板?
【问题讨论】:
-
你用的是什么编译器?一些编译器会阻止您将声明和定义分离到单独的模板文件中。
-
你真的为你的模板函数写了一个实现吗?
-
你也可以考虑使用 std::find 或 std::find_if
-
按值传递 v 和 name 的成本很高。改为通过 const 引用传递它们。
-
你说得对,埃里克,我还不太会使用 C++。至于find,看起来我应该更努力地寻找,但是如果它没有找到它为什么会最后返回呢?不存在的元素不应该有更好的返回值吗?
标签: c++ templates compiler-errors