Does a no-op “do nothing” function object exist in

2019-02-11 12:53发布

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 standard.

I grep'ed VC10's headers and came up with nothing. Can you help? It's bugging me! :)

edit: On second thought, the new functor I was remembering was probably the unrelated std::default_deleter.

4条回答
一纸荒年 Trace。
2楼-- · 2019-02-11 13:20

How about this?

// Return a noop function 
template <typename T>
struct noop
{
  T return_val;

  noop (T retval = T ())
       :  return_val (retval)
  {
  }

  T
  operator (...)
  {
    return return_val;
  }
};

template <>
struct noop<void>
{
  void
  operator (...)
  {
  }
};

This should work for just about any use.

查看更多
兄弟一词,经得起流年.
3楼-- · 2019-02-11 13:40

You could always write a no-op lambda: []{}

查看更多
不美不萌又怎样
4楼-- · 2019-02-11 13:41

You was probably thinking about the identity function (std::identity and apparently it's removed in the current draft) that is not the same thing though.

查看更多
Emotional °昔
5楼-- · 2019-02-11 13:42

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<class A>
    void operator()(A a) const { (void)(a); }
    template<class A, class B>
    void operator()(A a, B b) const { (void)(a); (void)(b); }
    template<class A, class B, class C>
    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<typename P1, typename... Params>
    void operator()(P1 p1, Params... parameters) {
        (void)(p1);             // we do this just to remove warnings -- requires the recursion
        operator()(parameters...);
    }
};
查看更多
登录 后发表回答