【发布时间】:2011-05-15 07:38:00
【问题描述】:
网上有很多说明如何编写模板方法的文档,但没有太多关于如何调用它们,如何在代码中使用它们的例子。
我有一个这样的模板方法:
VectorConvertor.h
template <class T>
static void AppendToVector(std::vector<T> & VectorToBeAppended,
std::vector<T> & VectorToAppend);
VectorConvertor.cpp
template <class T>
void VectorConvertor::AppendToVector(std::vector<T> & VectorToBeAppended,
std::vector<T> & VectorToAppend)
{
for (std::vector::size_type i=0; i<VectorToAppend.size(); i++)
{
VectorToBeAppended.push_back(VectorToAppend.at(i));
}
}
代码中的使用尝试:
std::vector<uint8_t> InputData, OutputData;
// ...
VectorConvertor::AppendToVector(OutputData, InputData);
我编译这段代码没有任何错误。但是当我尝试使用这种方法时,会出现以下错误:
错误 LNK1120:1 个未解决的外部问题
和
错误 LNK2019:未解析的外部符号“public: static void __cdecl VectorConvertor::AppendToVector(class std::vector > &,class std::vector > &)” (??$AppendToVector@E@VectorConvertor@@SAXAEAV? $vector@EV?$allocator@E@std@@@std@@0@Z) 在函数“public: staticclass std::vector > __cdecl Utf8::WStringToUtf8(class std::basic_string,class std::allocator >)" (?WStringToUtf8@Utf8@@SA?AV?$vector@EV?$allocator@E@std@@@std@@V?$basic_string@_WU?$char_traits@_W@std@@V?$allocator @_W@2@@3@@Z)
当我不在我的代码中使用此方法时,我不会收到任何错误消息。我在调用它时做错了什么?我错过了什么吗?
我使用的是 Visual Studio 2010 Express Edition。
【问题讨论】:
-
没有帮助,但这些错误信息正是我停止使用 C++ 编码的原因。
-
为清楚起见,不要将
template method(这是一种设计模式)与class template member function和function template混淆。
标签: c++ function templates methods