Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
221 views
in Technique[技术] by (71.8m points)

c++ - Most terse and reusable way of wrapping template or overloaded functions in function objects

Scenario 1: a template function pred

template<typename T>
bool pred(T t) { /* return a bool based on t */ }

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 */ }
...

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);

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can create a macro like

#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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.8k users

...