28

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.

dean
  • 51
  • 1
  • 4
  • 8

4 Answers4

34

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

tzaman
  • 46,925
  • 11
  • 90
  • 115
  • 1
    I like this, but it doesn't work for the number of `std::conditional` s I have scattered about. And an empty `std::function` will throw on operator(). – dean Jun 06 '10 at 01:01
  • Yes but every `[]{}` would be a distinct type. I could see several advantages to having a single name for the no-op function. – Billy Donahue Mar 08 '21 at 17:07
2

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...);
    }
};
rerx
  • 1,133
  • 8
  • 19
0

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.

snk_kid
  • 3,457
  • 3
  • 23
  • 18
  • I had known of `identity` but dismissed it for being a unary. I recall having needed a generic default_deleter for something, six months ago... can't quite remember what for. – dean Jun 06 '10 at 20:52
-1

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.

Joe D
  • 2,855
  • 2
  • 31
  • 25
  • 2
    Note that this fails if you ever try to pass a non-trivially-copyable type as an argument to noop, because they do not work with ... – rerx Sep 09 '14 at 15:07