簡體   English   中英

在模板化的 function 中使用轉發的 arguments 以默認參數執行 function

[英]Use forwarded arguments in templated function to execute function with default parameters

我有一個模板化的 function auto Run(Func f, Args&&... args)可以接受 variadig arguments 和一個 function 來執行。

If the function I want to execute has default arguments set, I cannot use this function for my Run function whithout specifying every argument on its own. 請參見下面的示例:

#include <functional>

template<typename Func, typename ...Args>
auto Run(Func f, Args&&... args)
{
    return f(std::forward<Args>(args)...);
}

int Int(int a, int b = 2){ return a + b; }

int main()
{
    Run(Int, 3, 2); // does compile, because every parameter is set
    Run(Int, 3); // does not compile
}

有沒有一種方法可以在不改變我如何調用 function 的情況下實現兩者? 我只想在可能的情況下更改模板化 function

一種可能的解決方案(從 C++14 開始)是將Int() function 包裝在通用 lambda 中

 Run([](auto && ... as)
      { return Int(std::forward<decltype(as)>(as)...); }, 3, 2);
 Run([](auto && ... as)
      { return Int(std::forward<decltype(as)>(as)...); }, 3);

這樣編譯器直接管理Int() function 的調用,保持第二個參數的默認值的知識並使用它。

問題是參數默認值不是函數簽名的一部分,因此以下函數

int Int_0 (int a, int b){ return a + b; }
int Int_1 (int a, int b = 2){ return a + b; }
int Int_2 (int a = 1, int b = 2){ return a + b; }

是具有相同簽名的 function ,因此屬於相同類型( int(int, int) )。

如果您將Int_2()傳遞給 function 接受int(int, int)或推斷為int(int, int)的模板參數(如在您的Run()情況下),則默認值是寬松的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM