【发布时间】:2021-04-24 22:42:39
【问题描述】:
场景一:模板函数pred
template<typename T>
bool pred(T t) { /* return a bool based on t */ }
场景2:一组同名pred重载的函数
bool pred(A t) { /* return a bool based on t */ }
bool pred(B t) { /* return a bool based on t */ }
bool pred(C t) { /* return a bool based on t */ }
...
无论我们处于两种情况中的哪一种,最重要的是pred 不引用函数,因此它不能被传递,例如作为std::remove_if 的一元谓词。
因此,在这种情况下,可以方便地定义以下可以传递的对象,
auto constexpr predObj = [](auto t){ return pred(t); };
但是,一旦我对另一个一元谓词有类似的需求,我需要复制并粘贴该行并将两个名称更改为其他名称;同样,如果我需要对二元谓词这样做:
auto contexpr binPredObj = [](auto x, auto y){ return binPred(x, y); };
有没有一种自动制作的通用方法?我正在考虑类似的事情
auto funObj = fun2Obj(fun);
我觉得我所问的完全是不可能的,因为它需要传递 fun,因为它是一个函数对象,但事实并非如此,否则我不需要用它制作一个函数对象.但问绝不是犯罪,对吧?
【问题讨论】:
标签: c++ overloading overload-resolution function-templates function-object