'Pass template to function as an argument in c++
I want to create a queue of structure (Category) sorted based on a parameter (action). For that, I'm using std::priority_queue (pQueue) template. When I build the code, I get the following errors:
error: redefinition of ‘pQueue::pQueue()’-> Used#pragma onceto avoid multiple header file inclusions, still getting this error.error: use of deleted function ‘pQueue::pQueue(constpQueue&)’ note: ‘pQueue::pQueue(const pQueue&)’ is implicitly deleted because the default definition would be ill-formed:-> How do I define custom constructor which can incorporate the information as shown in the code below?error: ‘q’ was not declared in this scope(scope: queueWork in file.cpp) Where do I declare 'q'?
How do I resolve these errors?
The main objective is to queue the data when function() is executed multiple times and later on use that data. The below code snippets are a part of a bigger project. Hence, might miss out on a few details.
file.cpp
#include "File.h"
using namespace std;
pQueue::pQueue()
{
std::priority_queue<std::pair<int, Category*>> q;
}
pQueue::~pQueue()
{
}
void queueWork(std::priority_queue<std::pair<int, Category*>> q, int action, Category* data)
{
q.emplace(make_pair(action, data));
}
void doWork(std::priority_queue<std::pair<int, Category*>> q, bool flag)
{
while (true)
{
std::pair<int, Category*> queueElement;
queueElement = q.top();
Category* data = queueElement.second;
// Perform some operation, get return value
q.pop();
}
}
file.h
#pragma once
#include <queue>
#include <thread>
class pQueue
{
public:
pQueue() {
}
~pQueue() {
}
void queueWork(std::priority_queue<std::pair<int, Category*>> q, int action, Category* data);
private:
void doWork(std::priority_queue<std::pair<int, Category*>> q, bool flag);
};
main.cpp
#include "File.h"
bool function(Category* data)
{
bool result;
if (data)
{
// Will set action values later
auto action = 1;
pQueue::queueWork(Queue, action, data);
// TODO: Implement getResult function to get the return value
// result = pQueue.getResult()
}
return true;
}
Solution 1:[1]
In your file.h you do not only declare the constructor, but also define it:
class pQueue
{
public:
pQueue() {
flag = false;
}
Next, in your file.c file you redeclare the constructor:
pQueue::pQueue()
{
std::priority_queue<std::pair<int, Category*>> q;
}
That's not possible. C++ has the One Definition Rule. There must only be one definition here.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | codeling |
