c++模板-参数中类型/值不匹配

C++ template - type/value mismatch at argument

本文关键字:不匹配 类型 模板 参数 c++      更新时间:2023-10-16

我得到这些错误,

模板形参列表中参数1的类型/值不匹配'模板类sasengineequeue '

模板形参列表中参数2的类型/值不匹配'模板类sasengineequeue '

,但如果我使用std::string的SasEngineQueue类的模板参数,那是可以的,但正如下面的代码,如果我使用std::vector,有错误。为什么?


class SasEngine{
private:
    unsigned char addr;
    SasEngineQueue<std::vector, std::vector> sasQ;
    SasTCP_IP sasTransport;
};

template<typename exception_t, typename lp_t>
class SasEngineQueue{
public:
    ThreadSafeQueue<exception_t> exceptionQ;
    ThreadSafeQueue<lp_t> lpCmdQ;
    ThreadSafeQueue<lp_t> lpRspQ;
};

template<typename msgType>
class ThreadSafeQueue{
protected:
    queue<msgType> threadSafeQ;
    mutex mu;
public:
    int get(msgType& msg);
    void push(msgType msg);
    void pop();
};

template<typename msgType>
int ThreadSafeQueue<msgType>::get(msgType& msg){
    lock_guard<mutex> autoMutex(mu);
    if(threadSafeQ.empty()){
        //empty Queue
        return -1;
    }
    msg = threadSafeQ.front();
    return 0;
}
template<typename msgType>
void ThreadSafeQueue<msgType>::push(msgType msg){
    lock_guard<mutex> autoMutex(mu);
    threadSafeQ.push(msg);
}
template<typename msgType>
void ThreadSafeQueue<msgType>::pop(){
    lock_guard<mutex> autoMutex(mu);
    threadSafeQ.pop();
}
template int ThreadSafeQueue<std::vector>::get(std::vector& msg);
template void ThreadSafeQueue<std::vector>::push(std::vector msg);
template void ThreadSafeQueue<std::vector>::pop();
template int ThreadSafeQueue<std::string>::get(std::string& msg);
template void ThreadSafeQueue<std::string>::push(std::string msg);
template void ThreadSafeQueue<std::string>::pop();

您应该始终指出错误发生的确切位置-这使人们更容易回答。

无论如何,问题是,虽然std::string是一个类型(具体来说,std::basic_string<char>的类型定义),std::vector不是。这是一个模板,你需要指定vector包含的类型,例如std::vector<int>

您可能想让它适用于任何向量——不幸的是,这不起作用,因为显式实例化必须指定一个具体类型。