如何访问存储在结构中的模板函数?

时间:2018-01-29 17:17:41

标签: c++ c++11 templates variadic-templates

struct taskinfo{
    template <class callable, class... arguments>
    taskinfo(callable&& f, arguments&&... args){
        std::function<typename std::result_of<callable(arguments...)>::type()> task(std::bind(std::forward<callable>(f), std::forward<arguments>(args)...));
    }
};

void test2(int a)
{
    printf("%i\n", a);
    return;
}

int main()
{
    taskinfo t1(&test2,100);
    std::priority_queue<taskinfo> tasks;
    tasks.push(t1);
    //tasks.top(). Execute task
    return 0;
}

我需要通过弹出优先级队列来执行任务。我的目标是拥有一个带有任何返回类型和接受变量参数的函数的结构。

1 个答案:

答案 0 :(得分:1)

  

如何访问存储在结构中的模板函数?

struct中没有存储功能。

写作时

template <class callable, class... arguments>
taskinfo(callable&& f, arguments&&... args){
    std::function<typename std::result_of<callable(arguments...)>::type()> task(std::bind(std::forward<callable>(f), std::forward<arguments>(args)...));
}

您将task声明为构造函数的变量 local

在构造函数执行结束后立即销毁的变量。

如果您想在std::function中存储struct,则必须将其声明为struct的成员。但是你需要知道声明它的类型。

我的意思是......您肯定可以声明一个模板struct,其中包含std::function,其类型取决于struct模板参数

template <typname R, typename ... Args>
struct taskinfo
 { 
   std::function<R(Args...>)  task;
   // ...
 };

但您无法为非非模板taskinfo

声明模板(非静态)成员
struct taskinfo
 {
   template <typname R, typename ... Args> // <-- ERROR
   std::function<R(Args...)>  task;        // <-- ERROR 
   // ...
 }