无法解决“未定义引用...”错误

时间:2014-02-13 08:00:01

标签: c++ codeblocks

此代码存在问题,我无法理解。 似乎问题发生在链接阶段,因为我用谷歌搜索,但在我的情况下,我认为我的代码有问题,而不是工具链,但我只是在经过数小时和数小时的尝试后无法解决。如果你能帮助我纠正它,我会很高兴的。 我正在使用Code :: Blocks,以及最新版本的MinGW。

的main.cpp

#include <iostream>
#include <string>
#include "threadsafequeue.hpp"
using namespace std;

int main(){
    threadsafe_queue<string> Q;
    threadsafe_queue<string> X;
    X.empty();
    try{
        string s;
    }catch(empty_queue ex){
        cout << ex.what() << endl;
    }
    return 0;
}

threadsafe_queue.cpp

#include "threadsafe_queue.hpp"

template <typename T>
threadsafe_queue<T>::threadsafe_queue(const threadsafe_queue& other){
    std::lock_guard<std::mutex> lock(other.m);
    threadsafe_queue<T>::data = other.data;
}

template <typename T>
void threadsafe_queue<T>::push(T new_value){
    std::lock_guard<std::mutex> lock(threadsafe_queue<T>::m);
    threadsafe_queue::data.push(new_value);
}

template <typename T>
std::shared_ptr<T> threadsafe_queue<T>::pop(){
    std::lock_guard<std::mutex> lock(threadsafe_queue<T>::m);
    if(data.empty()) throw empty_queue();
    std::shared_ptr<T> const res(std::make_shared<T>(threadsafe_queue<T>::data.front()));
    threadsafe_queue<T>::data.pop();
    return res;
}

template <typename T>
void threadsafe_queue<T>::pop(T& value){
    std::lock_guard<std::mutex> lock(threadsafe_queue::m);
    if(data.empty()) throw empty_queue();
    value = threadsafe_queue::data.front();
    threadsafe_queue::data.pop();
}

template <typename T>
bool threadsafe_queue<T>::empty(){
    std::lock_guard<std::mutex> lock(threadsafe_queue<T>::m);
    return threadsafe_queue<T>::data.empty();
}

threadsafe_queue.hpp

#include <exception>
#include <memory>
#include <mutex>
#include <queue>

#ifndef THREADSAFE_QUEUE_HPP_INCLUDED
#define THREADSAFE_QUEUE_HPP_INCLUDED

struct empty_queue : std::exception
{
    virtual const char * what() const throw()
    {
        return "The Queue is Empty.";
    };
};

template <typename T>
class threadsafe_queue
{
private:
    std::queue<T> data;
    mutable std::mutex m;
public:
    threadsafe_queue() {};
    threadsafe_queue(const threadsafe_queue& other);

    threadsafe_queue& operator= (const threadsafe_queue&) = delete;

    void push(T new_value);

    std::shared_ptr<T> pop();

    void pop(T& value);

    bool empty();
};

#endif // THREADSAFE_QUEUE_HPP_INCLUDED

错误是:

  

... \ ThreadSafeQueue \ main.cpp | 9 |未定义引用   `threadsafe_queue ::空()'|

2 个答案:

答案 0 :(得分:4)

将所有内容从threadsafe_queue.cpp移至threadsafe_queue.hpp

Why can templates only be implemented in the header file?

或者,如果您希望将模板的声明和实现分开,请将threadsafe_queue.cpp重命名为threadsafe_queue.tpp(不是真的需要,只是为了更清晰)并将其包含在{{1}的末尾文件。

答案 1 :(得分:1)

您必须在main.cpp中包含您的实施文件:

threadsafe_queue.cpp

实际上你的模板定义必须在你的threadsafe_queue.hpp文件中,否则模板将不会被实例化。