将智能指针传递到模板类成员函数时出现编译错误

Compilation Error on passing smart pointer to a template class member function

本文关键字:函数 成员 错误 编译 指针 智能      更新时间:2023-10-16

我在传递时遇到编译错误 1. 唯一的 PTR 到模板类成员函数 2. 指向模板类成员函数的唯一指针的内容

我正在尝试将数据推送到向量内。数据为模板类型。 这里的唯一指针用于在每次数据到达时在堆上创建一个内存,然后将该数据存储到向量中。 甚至复制指向新位置的指针也可以推送到矢量内部。 我都试过了 1. 使用 T 项捕获数据;//下面提到的代码 2. 使用 std::unique_ptr 和 item 捕获带有引用的唯一指针; 示例代码是长代码的代码片段

#include <stdio.h>
#include<iostream>
#include<vector>
#include <mutex>
#include <condition_variable>
#include <boost/any.hpp>
using namespace std;
namespace amb
{
template <typename T>
class Queue
{
public:
Queue(bool unique = false, bool blocking = false)
:mUnique(unique), mBlocking(blocking)
{
}
virtual ~Queue()
{
}
int count()
{
std::lock_guard<std::mutex> lock(mutex);
return mQueue.size();
}
T pop()
{
std::unique_lock<std::mutex> lock(mutex);
uint16_t i =0;
if(mBlocking)
{
if(!mQueue.size())
{
cond.wait(lock);
}
}
if(!mQueue.size())
{
throw std::runtime_error("nothing in queue");
}
auto itr = mQueue.begin();
T item = *itr;
mQueue.erase(itr);
return item;
}
virtual void append(T  item)
{
std::lock_guard<std::mutex> lock(mutex);
mQueue.push_back(item);
}
void remove(T item)
{
std::lock_guard<std::mutex> lock(mutex);
removeOne(&mQueue, item);
}
std::vector<T> get_Val()
{
return mQueue;
}
private:
bool mBlocking;
bool mUnique;
std::mutex mutex;
std::condition_variable cond;
std::vector<T> mQueue;
};
}
class AbstractPropertyType
{
public:
AbstractPropertyType(){}
virtual ~AbstractPropertyType()
{
}
virtual AbstractPropertyType* copy() = 0;
boost::any anyValue()
{
return mValue;
}
protected:
boost::any mValue;
};
template <typename T>
class BasicPropertyType: public AbstractPropertyType
{
public:
BasicPropertyType(): AbstractPropertyType("")
{
mValue = T();
}
AbstractPropertyType* copy()
{
return new BasicPropertyType<T>(*this);
}
};
amb::Queue<AbstractPropertyType*> prop;
void updateProperty(AbstractPropertyType * val)
{
std::unique_ptr<AbstractPropertyType> temp_data =  std::unique_ptr<AbstractPropertyType>(val->copy());
prop.append(temp_data);
}
int main() {
//code
uint8_t x = 10;
uint8_t * test_val = &x;
boost::any to_check = (uint8_t *)test_val;
AbstractPropertyType * value = new BasicPropertyType<uint32_t>;
updateProperty(value);
}

主要摩托车是 1. 将模板数据的内容推送到向量中 2. 指向

编译错误: prog.cpp: 在函数 'void updateProperty(AbstractPropertyType*)' 中: prog.cpp:109:26:错误:调用"amb::队列::追加(std::unique_ptr&)"没有匹配函数 prop.append(temp_data); ^

amb::Queue<AbstractPropertyType*> prop;

因此,prop.append()采用类型AbstractPropertyType*的参数,但您正在发送类型std::unique_ptr<AbstractPropertyType>temp_data。由于append函数需要原始指针,因此应在其中传递原始指针。没有从unique_ptr<T>T*的隐式转换。

void updateProperty(AbstractPropertyType * val)
{
std::unique_ptr<AbstractPropertyType> temp_data =  std::unique_ptr<AbstractPropertyType>(val->copy());
prop.append(temp_data.get());
}