C++ 函式庫 - operator==, !=(std::function)



描述

它將一個 std::function 與一個空指標進行比較。空函式(即沒有可呼叫目標的函式)比較相等,非空函式比較不相等。

宣告

以下是 std::function 的宣告。

template< class R, class... ArgTypes >
bool operator==( const std::function<R(ArgTypes...)>& f, std::nullptr_t )

C++11

template< class R, class... ArgTypes >
bool operator==( const std::function<R(ArgTypes...)>& f, std::nullptr_t )

引數

f − 用於比較函式。

返回值

異常

noexcep − 不丟擲任何異常。

示例

下面的例子解釋了 std::function。

#include <functional>
#include <iostream>

using SomeVoidFunc = std::function<void(int)>;

class C {
   public:
      C(SomeVoidFunc void_func = nullptr) :
         void_func_(void_func) {
            if (void_func_ == nullptr) { 
               void_func_ = std::bind(&C::default_func, this, std::placeholders::_1);
            }
            void_func_(9);
         }
 
         void default_func(int i) { std::cout << i << '\n'; };
 
   private:
      SomeVoidFunc void_func_;
};
 
void user_func(int i) {
   std::cout << (i + 1) << '\n';
}

int main() {
   C c1;
   C c2(user_func);
}

讓我們編譯並執行上面的程式,這將產生以下結果:

9
10
functional.htm
廣告