jeudi 30 août 2018

How to specify an templatized alias' generic type in a container

I have a class Task:

template <typename T>
class Task {

    Task(const std::function<T()>& func) 
        : m_func(func)
    {
        // some stuff here
    }

    std::shared_ptr<T> getValue() {
        return m_value;
    }

    void execute() {
        m_value = std::make_shared<T>(m_func());
    }


    std::shared_ptr<T> m_value;  
    std::function<T()> m_func;  
}

Now, I want to alias this Task class to a shared_ptr so I do the following...

template <typename T> using TaskPtr = std::shared_ptr<Task<T> >;

I have another class that will store a container of of TaskPtr, I would like for the consumer of the api to specify T when calling addTask as follows.

Class X {
    // some boiler plate code
    template <typename T> 
    addTask(TaskPtr<T> task) {
         m_queue.push(task);
    }

    void loop() {
        // do some stuff
        auto item = m_queue.front();
        item->execute();
        m_queue.pop();
        // continue looping
    }

 std::queue<TaskPtr<T> > m_queue; 
}

I was wondering what the best way to do this would be. This code gives me the error that T is undefined. Duh! I need to add template <tyepname T> above my m_queue definition, that makes sense. When I do that, I get that I am putting the keyword typedef in an incorrect location. When I remove the template declaration and the T to just have std::queue<Taskptr> m_queue;, it tells me I am missing a template argument. Which makes sense, except I don't understand where it should go.

I have searched for an answer and couldn't find anything. What is the correct syntactical implementation for what I am trying do?

Aucun commentaire:

Enregistrer un commentaire