【发布时间】:2025-11-21 11:00:02
【问题描述】:
C++ std 命名空间包含辅助函数 std::not1 和 std::not2。它们都分别采用一元或二元谓词函子,并分别返回 std::unary_negate 或 std::binary_negate 谓词。
我想知道是否应该使用一些模板魔法来拥有
template<typename Predicate> inline
enable_if_t<is_unary_predicate<Predicate>::value, unary_negate<Predicate> >
not_(Predicate const&pred)
{ return unary_negate<Predicate>{pred}; }
template<typename Predicate> inline
enable_if_t<is_binary_predicate<Predicate>::value, binary_negate<Predicate> >
not_(Predicate const&pred)
{ return binary_negate<Predicate>{pred}; }
它区分参数pred 传递以返回适当的谓词。当然,在某些奇怪的情况下,传递的对象 pred 具有两种类型的运算符(一元和二元),此时这不起作用,但可以在不使用此辅助函数的情况下处理这些情况。
【问题讨论】:
-
not是关键字,因此无法使用 -
@DieterLücking 好吧,那就叫它
not_()吧。 -
@RahulTripathi 好地方。我引用的 cppreference 实际上声明这些函数在 C++14 之前是标准的一部分,因此在此之后不推荐使用。所以,我认为,这回答了它。不幸的是,cppreference 和您引用的来源都没有提供替代方案。
-
@Walter 替代方案是 lambdas。
-
@Walter:- 下一页说:
Being able to use lambda is really an improvement here
标签: c++ template-meta-programming sfinae