我試圖創建一個通用包裝器函數,該函數將一個函數作爲模板參數,並將該函數作爲其參數使用相同的參數。例如:函數作爲模板參數的C++函數調用包裝器
template <typename F, F func>
/* return type of F */ wrapper(Ts... Args /* not sure how to get Ts*/)
{
// do stuff
auto ret = F(std::forward<Ts>(args)...);
// do some other stuff
return ret;
}
該解決方案需要被強制轉換爲與相同類型func
函數指針,這樣我可以將它傳遞給一個C API。換句話說,解決方案需要是一個功能而不是一個功能對象。最重要的是,我需要能夠在包裝函數中工作。
如果內嵌評論是不明確的,我希望能夠做到像下面這樣:
struct c_api_interface {
int (*func_a)(int, int);
int (*func_b)(char, char, char);
};
int foo(int a, int b)
{
return a + b;
}
int bar(char a, char b, char c)
{
return a + b * c;
}
c_api_interface my_interface;
my_interface.func_a = wrapper<foo>;
my_interface.func_b = wrapper<bar>;
我找了相關的帖子,發現這些,但他們都不是很什麼我正在努力。大多數這些帖子都涉及功能對象。我試圖做甚至可能嗎?
Function passed as template argument
Function wrapper via (function object) class (variadic) template
How does wrapping a function pointer and function object work in generic code?
How do I get the argument types of a function pointer in a variadic template class?
Generic functor for functions with any argument list
爲了迴應前兩個回答,我編輯了這個問題,以清楚地說明我需要能夠在包裝函數中進行工作。在調用包裝的函數)
謝謝!我將它改爲接受的答案,因爲它比@TC短,只使用函數而不是結構,使用'std :: forward',(作爲意見)更容易理解,因爲你沒有使用模板參數專門化。 – Eric
儘管我不得不承認std :: forward只是在那裏,因爲我嘗試了一些可以在MSVC下編譯的東西,然後認爲「啊擰它,不會發生......但是,嘿,繼續前進」;-) – VolkerK
什麼是爲wrapper聲明一個別名的正確方法,它看起來像一個正常的函數來調用?就像'使用a_wrapped = wrapper;'(但這個不起作用)。 –
eudoxos