我不明白为什么编译不正确,链接器报告缺少符号:
体系结构 x86_64 的 undefined symbol : “bool swinadventure::Utils::is_last<__gnu_cxx::__normal_iterator >>, std::vector >>(__gnu_cxx::__normal_iterator >>, std::vector > const&)”,引用自: Inventory.cpp.o 中的 swinadventure::Inventory::get_item_list(std::string, std::string)
因为在此过程中的早期我也看到了这个错误:/usr/bin/ranlib: file: liblibswinadventure.a(Utils.cpp.o) has no symbols
我假设它没有编译utils 文件由于某种原因正确。
作为引用,我在安装并链接了大多数自制工具的 Mac OS X 10.7 系统上使用 CMake。
Utils.h
#ifndef UTILS_H_
#define UTILS_H_
#include <vector>
namespace swinadventure {
/**
* Static class for various utilities and helper functions
*/
class Utils {
public:
template <typename Iter>
static Iter next_iterator(Iter iter);
template <typename Iter, typename Cont>
static bool is_last(Iter iter, const Cont& cont);
};
} /* namespace swinadventure */
#endif /* UTILS_H_ */
Utils.cpp
#include "Utils.h"
namespace swinadventure {
/**
* Returns the next iterator
* http://stackoverflow.com/questions/3516196/testing-whether-an-iterator-points-to-the-last-item
* @param iter
* @return
*/
template <typename Iter>
Iter Utils::next_iterator(Iter iter) {
return ++iter;
}
/**
* Checks if the iterator is the last of the vector array
* http://stackoverflow.com/questions/3516196/testing-whether-an-iterator-points-to-the-last-item
* @param iter iterator
* @param cont vector array
* @return
*/
template <typename Iter, typename Cont>
bool Utils::is_last(Iter iter, const Cont& cont)
{
return (iter != cont.end()) && (next_iterator(iter) == cont.end());
}
} /* namespace swinadventure */
最佳答案
将您的模板函数定义移动到标题。
链接器告诉您在编译 Inventory.cpp
时,需要一个特殊的 Utils::is_last
实例化,但定义无法创建它.
并且在编译 Utils.cpp
时,Utils::is_last
的定义可用,但不需要实例化。
因此两个源文件都无法在编译时创建该函数。
关于c++ - 使用类的静态函数模板成员的链接器错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12438852/