调用 header 中定义的模板函数时出现 C++ 链接器错误

标签 c++ c++11 templates linker

调用模板函数时出现链接错误,但链接器错误似乎并未指向模板函数。它似乎指向函数中的共享指针。我的带有模板函数的类:

class Blackboard {
    public:
    template<class T>
    bool setValue(std::string key, T* value) {
        std::shared_ptr<T> ptr(T);
        boost::any v = ptr;
        auto it = map.insert(std::pair<std::string, boost::any>(key, v));
        return it.second;
    }
}

大多数类似的问题都说将所有实现都放在 header 中,我已经这样做了。链接错误发生在调用此函数的类中。调用黑板的示例类:

class Example {
    void foo(Blackboard* blackboard) {
        int* i = new int;
        *i = 0;
        blackboard->setValue<int>("some key", i);
    }
}

错误:

Error LNK2019 unresolved external symbol "class std::shared_ptr<int> __cdecl ptr(int)" (?ptr@@YA?AV?$shared_ptr@H@std@@H@Z) referenced in function "public: bool __cdecl BehaviorTree::Blackboard::setValue<int>(class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >,int *)" (??$setValue@H@Blackboard@BehaviorTree@@QEAA_NV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@PEAH@Z)

Blackboard类和 Example类是 Visual Studio 静态库项目的一部分。使用静态库编译程序时出现链接错误。

我很难找到解决此问题的方法,因此我们将不胜感激!

最佳答案

问题好像是你写的

std::shared_ptr<T> ptr(T);

代替

std::shared_ptr<T> ptr(value);

关于调用 header 中定义的模板函数时出现 C++ 链接器错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44832543/

相关文章:

c++ - 将数据从 const void *data 转换为 double

c++ - 在 Mac OSX 上的 Sublime Text 3 中运行 C++

c++ - 在抛出 'std::length_error' 实例后调用终止

c++ - 使用模板函数计算数组中元素的数量

C++ 解决方法 : `invalid initialization of reference of type ‘C*&’ from expression of type ‘B*’

C++ 将数组复制到指针参数

c++ - 仅更改 C++ 模板中类型的一部分

c++ - decltype 需要实例化对象

c++ - 为什么只有在列表初始化的情况下才会出现缩小转换警告?

C++ 模板 vector 操作重载