c++ - 使用类的静态函数模板成员的链接器错误

标签 c++ templates vector compiler-errors cmake

我不明白为什么编译不正确,链接器报告缺少符号:

体系结构 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/

相关文章:

php - 修改 Woocommerce 模板文件以按产品类别显示产品

javascript - 如何在 Emscripten 生成的代码中使用 C++ 分配的数组?

c++ - 如何对包含 pair<int,int> 元素的 vector 进行排序?根据比较功能进行排序

angularjs - 模态内的 NgMap(谷歌地图) - 不显示第二次

c++ - 具有 get 函数的模板类总是返回引用,

matlab - 基于两个向量 MATLAB 构造此矩阵

c++ - 正确取消对指针的引用迭代器

c++ - 与 std::inserter 相比,std::back_inserter 有什么好处?

c++ - 声明一个以我自己的类作为值类型的映射

c++ - 委派构造函数和模板