在函数对象中包装模板或重载函数的最简洁和可重用的方法 [英] Most terse and reusable way of wrapping template or overloaded functions in function objects
问题描述
场景一:模板函数pred
template<typename T>
bool pred(T t) { /* return a bool based on t */ }
场景二:一组重载同名的函数pred
Scenario 2: a set of functions overloaded on the same name 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
的一元谓词.
Whichever of the two scenarii we're in, the bottom line is that pred
does not refer to a function, and so it cannot be passed around, e.g. as a unary predicate to std::remove_if
.
因此在这种情况下定义以下可以传递的对象很方便,
Therefore it is convenient in this case to define the following object which can be passed around instead,
auto constexpr predObj = [](auto t){ return pred(t); };
但是,一旦我对另一个一元谓词有类似的需求,我需要复制并粘贴该行并将两个名称更改为其他名称;同样,如果我需要为二元谓词这样做:
However, as soon as I have a similar need for another unary predicate, I need to copy and paste that line and change the two names to something else; similarly if I need to do that for a binary predicate:
auto contexpr binPredObj = [](auto x, auto y){ return binPred(x, y); };
是否有自动制作的通用方法?我正在考虑类似的事情
Is there a general way of making this automatically? I'm thinking of something like
auto funObj = fun2Obj(fun);
我觉得我问的是不可能的,因为它需要传递 fun
因为它是一个函数对象,它不是,否则我不需要做一个函数对象出来了.但问永远不会犯罪,对吧?
I have the feeling that what I ask is not possible exactly because it would require passing fun
as it was a function object, which it isn't, otherwise I wouldn't need to make a function object out of it. But asking is never crime, right?
推荐答案
你可以像这样创建宏
#define FUNCTORIZE(func) [](auto&&... val) \
noexcept(noexcept(func(std::forward<decltype(val)>(val)...))) -> decltype(auto) \
{return func(std::forward<decltype(val)>(val)...);}
它将让您将任何可调用对象包装到一个闭包对象中.你会像这样使用它
which will let you wrap any callable into a closure object. You would use it like
auto constexpr predObj = FUNCTORIZE(pred);
这篇关于在函数对象中包装模板或重载函数的最简洁和可重用的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!