Does a no-op “do nothing” function object exist in C++(0x)?

后端 未结 4 1554
春和景丽
春和景丽 2021-01-03 20:16

I realize this is a ludicrous question for something that takes less than 2 seconds to implement. But I vaguely remember reading that one was introduced with the new standar

4条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-03 20:37

    I use this as a drop-in no-op for cases where I expect a functor that does not return any value.

    struct VoidNoOp {
        void operator()() const { }
        template
        void operator()(A a) const { (void)(a); }
        template
        void operator()(A a, B b) const { (void)(a); (void)(b); }
        template
        void operator()(A a, B b, C c) const { (void)(a); (void)(b); (void)(c); }
    };
    

    Here is a C++11 variation for arbitrary numbers of parameters:

    struct VoidNoOp {
        void operator()() const { };
        template
        void operator()(P1 p1, Params... parameters) {
            (void)(p1);             // we do this just to remove warnings -- requires the recursion
            operator()(parameters...);
        }
    };
    

提交回复
热议问题