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

那年仲夏 提交于 2019-11-30 17:07:54
tzaman

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

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.

rerx

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

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!