简体   繁体   English

调用标头中定义的模板函数时,C ++链接器错误

[英]C++ linker error when calling template function that is defined in header

I'm getting a linking error when calling a template function, but the linker error does not seem to point to the template function. 调用模板函数时出现链接错误,但是链接器错误似乎没有指向模板函数。 It seems to point to the shared pointer in the function. 似乎指向函数中的共享指针。 My class with the template function: 我的类具有模板功能:

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;
    }
}

Most similar questions say put all implementation in the header, which I have done. 大多数类似的问题都说所有实现都放在标头中,这已经完成了。 The linking error happens in the class that calls this function. 链接错误发生在调用此函数的类中。 Example class that calls blackboard: 调用黑板的示例类:

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

The error: 错误:

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)

Both the Blackboard class and the Example class are part of a visual studio static lib project. Blackboard类和Example类都是Visual Studio静态lib项目的一部分。 The linking error occurs when compiling a program using the static library. 使用静态库编译程序时发生链接错误。

I'm having difficulty finding a solution to this problem, so any help would be appreciated! 我很难找到解决此问题的方法,因此将不胜感激!

The problem seems to be that you wrote 问题似乎是您写的

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

instead of 代替

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM