【发布时间】:2022-01-07 16:57:21
【问题描述】:
我想用 c++17 编译下面的代码,这样我就可以传递任何具有特定签名 int(int) 的函数 (lambda),同时还允许使用默认参数:
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;
^
我不明白为什么我传递lambda时可以初始化成员f_而默认的lambda参数不能?
同时,有没有更好的方法来做到这一点?
【问题讨论】:
标签: c++ templates lambda default-arguments