2016-02-05 135 views
-1

如何調用傳遞給模板函數參數的函數? 我嘗試的功能添加到後,我得到它的工作,所以我可以調用所有功能在矢量,有點像一個回調矢量使用傳遞給模板函數的參數調用函數

#include <Windows.h> 
#include <iostream> 
#include <functional> 

template <typename... T> 
void RunFunction(std::function<void> f, T... args) 
{ 
    f(args); 
} 

void testFunction(int x, int y) 
{ 
    std::cout << (x + y); 
    return; 
} 


int main() 
{ 
    RunFunction(testFunction, 1, 3); 
} 
+0

'std :: function '是無稽之談,你需要推導'f''的類型。你也忘了在調用'f'的時候擴展'args'。 – LogicStuff

回答

3

你可能想:

template <typename F, typename... Ts> 
void RunFunction(F f, Ts&&... args) 
{ 
    f(std::forward<Ts>(args)...); 
} 

void testFunction(int x, int y) 
{ 
    std::cout << (x + y); 
} 

int main() 
{ 
    RunFunction(testFunction, 1, 3); 
} 

由於

std::function<void>不是你想要的,而是std::function<void(Ts...)>
f(args);應該是f(args...)

然後Sig不能推斷出std::function<Sig>testFunction

+0

哦,哇,那有什麼作用,有沒有什麼機會可以告訴我,我可以如何將它添加到一個std:vector來調用它,在所有具有不同數量的參數的3個函數循環中調用它?或者我應該問一個關於如何做的新問題?謝謝 – ramafe

+0

@ramafe:不清楚你想要什麼。抱歉。 – Jarod42

+0

我希望能夠將函數+其參數存儲在向量中,然後在需要時再調用它。我一直在尋找谷歌找到和即時通訊沒有多少運氣 – ramafe

相關問題