【发布时间】:2020-08-26 03:56:53
【问题描述】:
#include <functional>
template <typename M>
M g(std::function<M(int)> f) {
return f(0);
}
int main() {
g([](int x){return x + 1;});
return 0;
}
我想表达类似“传递给函数g 的(唯一)参数应该是一个以int 作为参数类型的可调用对象”。
G++ 9.3.0 说
prog.cc: In function 'int main()':
prog.cc:8:31: error: no matching function for call to 'g(main()::<lambda(int)>)'
8 | g([](int x){return x + 1;});
| ^
prog.cc:3:3: note: candidate: 'template<class M> M g(std::function<M(int)>)'
3 | M g(std::function<M(int)> f) {
| ^
prog.cc:3:3: note: template argument deduction/substitution failed:
prog.cc:8:31: note: 'main()::<lambda(int)>' is not derived from 'std::function<M(int)>'
8 | g([](int x){return x + 1;});
| ^
上述尝试有什么问题?我应该如何实现这个意图?
您可能希望在 Wandbox here 上查看代码 sn-p。
【问题讨论】:
-
你为什么觉得你需要这样强制执行?
-
您希望传入的函数以
int作为参数类型,还是接受任何可以使用int调用的函数? -
为什么要这样限制?与
template <typename M> auto f(M m) { return m(0); }相比,它到底给你带来了什么? coliru.stacked-crooked.com/a/3a9e94caf357f0b9 -
@n.'pronouns'm。我想强制
m的参数类型正好是int,并禁止f([](double x) { // .... });这样的调用。 -
@cigien 我希望传入的函数具有
int作为参数的类型。
标签: c++