我想用 c 17 編譯下面的代碼,以便我可以傳遞具有特定簽名的任何函式 (lambda) int(int),同時還允許默認引數:
template <class F = int(int)> // for deduction
struct A{
A(F f = [] (int x){return x;}) : f_{f} {}
F f_;
};
int main() {
A work([](int x){return x 1;});
A not_work; // compile error.
}
但是,clang 會發出一個錯誤:
a.cpp:6:4: error: data member instantiated with function type 'int (int)'
F f_;
^
a.cpp:11:4: note: in instantiation of template class 'A<int (int)>' requested here
A not_work;
^
我不明白為什么f_當我傳遞 lambda 時可以初始化成員,而默認的 lambda 引數不能?
同時,有沒有更好的方法來做到這一點?
uj5u.com熱心網友回復:
正如錯誤訊息所說,您不能宣告具有函式型別的資料成員,如int(int).
當將 lambda 傳遞給建構式時,模板引數F將被 CTAD 推匯出為 lambda 閉包型別(C 17 起);當不傳遞任何內容時F將使用默認引數int(int),資料成員f_的型別也是int(int)如此,這會導致錯誤。
您可以使用函式指標型別(沒有捕獲的lambdas可以隱式轉換為函式指標)或std::function<int(int)>. 例如
template <class F = int(*)(int)> // for deduction
struct A{
A(F f = [] (int x){return x;}) : f_{f} {}
F f_;
};
或者
template <class F = std::function<int(int)>> // for deduction
struct A{
A(F f = [] (int x){return x;}) : f_{f} {}
F f_;
};
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/371194.html
