2015-09-01 35 views
3

我有兩個以下功能:C++不需要的類型扣

template<class F, class... Args> 
    auto runAt(F&& function, const std::chrono::steady_clock::time_point& timePoint, Args&&... args) 
    -> std::future<typename std::result_of<F(Args...)>::type> { 
    using return_type = typename std::result_of<F(Args...)>::type; 
    std::future<return_type> futureResult; 

    auto packagedTask = std::make_shared<std::packaged_task<return_type()> > 
    (std::bind(std::forward<F>(function), std::forward<Args>(args)...)); 
    futureResult = packagedTask->get_future(); 

    this->addTask(Task([this, packagedTask]() { 
     (*packagedTask)(); 
     }), timePoint); 
    return futureResult; 
    } 

    void runAt(const Task& task, 
      const std::chrono::steady_clock::time_point& timePoint); 

以我的main.cpp文件,我創建任務對象,分配一個函數,並推到我的調度器。 runAt是調度程序的功能。

這是代碼:

... // Task initialization 
scheduler.runAt(task, std::chrono::steady_clock::now()); 

的問題是,所述模板函數被調用,而不是一個採取任務作爲參數。我明白這兩個函數都是有效的,因爲第一個參數是模板化的,可變參數對象是空的。

我有兩個問題:

1)如何調用第二個方法(考慮返回類型是不一樣的)

2)不是很重要,但我很好奇,想知道這是如何編譯

auto packagedTask = std::make_shared<std::packaged_task<return_type()> > 
    (std::bind(std::forward<F>(function), std::forward<Args>(args)...)); 
+0

這兩個函數有不同的名字:'runTaskAt'和'runAt'。 – wilx

+0

'runTask'和'runTaskAt'不會超載。他們在你的代碼中有相同的名字嗎? – 0x499602D2

+0

對不起,我只是在寫文章之前修改了名字,我編輯了我的文章 – Luc

回答

5

1)如何調用第二種方法中不會失敗(考慮返回類型是不一樣的)

限制第一個。

template<class F, class... Args, 
     class = std::enable_if_t<!std::is_same<std::decay_t<F>, Task>{}>> 
auto runAt(F&& function, const std::chrono::steady_clock::time_point& timePoint, 
      Args&&... args) 
    -> std::future<typename std::result_of<F(Args...)>::type> { 
    /* ... */ 
} 

順便提及,

auto packagedTask = std::make_shared<std::packaged_task<return_type()> > 
(std::bind(std::forward<F>(function), std::forward<Args>(args)...)); 

不正確。 bind對嵌套綁定和佔位符做了特殊處理,因爲您計算的返回類型爲typename std::result_of<F(Args...)>::type,因此您不需要這些特殊處理。

+0

謝謝,這正是我的預期 – Luc