![](/img/trans.png)
[英]How can I pass a function as argument regardless of its return type in C++ ? (without using a template parameter for the passed function)
[英]c++ How can i save function return type for lambda function without template?
我正在嘗試創建 class 可以保存 function 指針、arguments 和返回類型。
我的 class 保存 function
// Here i can't pass temlpate because next step for me is creating array of CFnSaver ('std::vector<CFnSaver*>')
// template<typename T>
class CFnSaver
{
public:
// i can't use template here, compiler throw an error
// template<typename T>
std::function<int()> savedFn;
template<typename ... Args>
constexpr bool Save(void* pFn, Args ... args)
{
if (!pFn) return false;
// creating lambda function
auto lambdaFn = [pFn, args...]()
{
// I need to get function return type, not just hardcode 'int' (as i did)
using tempFn = int(*)(Args ...);
auto tempFunc = reinterpret_cast<tempFn>(pFn);
return tempFunc(args...);
};
// Here i can call original function and get result, e.g. '5', but i don't need it here
// auto res = lambdaFn();
// saving lambda to std::function
savedFn = lambdaFn;
return !!savedFn;
}
inline CFnSaver() {};
template<typename ... Args>
inline CFnSaver(void* pFn, Args ... args) { Save(pFn, args...); }
bool const operator ! () const { return(!savedFn); }
explicit operator bool() const { return !!savedFn; }
};
使用示例:
int printSum(int a, int b)
{
int sum = a + b;
printf_s("%d\n", sum);
return sum;
}
int main()
{
CFnSaver cfn(printSum, 2, 3);
// I need to get return of this function (now it's hardcoded to int)
auto res = cfn.savedFn();
return 0;
}
我還可以創建另一個版本的 function,將另一個變量作為 ref 傳遞。 但我對此並不滿意。
void printSum(int a, int b, int& result)
{
int sum = a + b;
printf_s("%d\n", sum);
result = sum;
}
int main()
{
int result = 0;
CFnSaver cfn(printSum, 2, 3, result);
cfn.savedFn();
return 0;
}
我想我需要另一種方法來保存 function 或者我錯過了一些方法來做到這一點,我們將不勝感激。
對不起,我的英語不好。
我試過模板 class、模板 function,將變量作為 ref 傳遞。
可悲的是,我認為不使用模板是不可能的。
我的建議是不要使用保存函數的數組,而是創建一個 lambda 來調用它們並使用它。 lambda 甚至可以采用布爾值數組來指定是否在必要時調用特定函數。
編輯:
如果返回類型相同,或者函數可以分組到具有相同返回類型的列表中,則可以使用std::bind
。 如果:
std::vector<std::function<int()> vec {
AddNumbers, // AddNumbers(int, int) adds two numbers
std::bind(AddNumbers, std::placeholders::_1, 3) // Adds three to a number, usage example: vec[1](2); would return 5
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.