前言
看到资料上演示base::Bind类成员函数,试试。
不能跑的实现都是假的。
实验
// @file Z:\chromium\src\base\test\test_by_me\main.cpp
// @brief write some test code to study chromium project
/**
# cd /d Z:\chromium\src\
# gn --ide=vs args out\my_x86_d
# gn ls out\my_x86_d > d:\my_tmp\gn_list_target.log
# 新加的测试工程位置//base/test:test_by_me
# autoninja -C out\my_x86_d test_by_me
*/
#include <stdlib.h>
#include <stdio.h>
#include <memory>
#include <set>
#include <utility>
#include "base/bind.h" // for base:Bind()
#include "base/logging.h" // for LOG()
#include "base/callback.h" // for base ::Callback()
#include "base\memory\scoped_refptr.h" // for scoped_refptr<>
#include "base\memory\ref_counted.h"// for RefCountedThreadSafe<>
#define PROG_NAME "test_my_me"
void fn_test();
void fn_test_bind_global_function();
void fn_test_bind_class_member_function();
int main(int argc, char** argv)
{
printf(">> %s\n", PROG_NAME);
// printf("hello chromium\n");
fn_test();
system("pause");
return EXIT_SUCCESS;
}
/** run result
debug.log
[1217/140711.850:WARNING:main.cpp(69)] >> fn_test_bind_class_member_function()
[1217/140711.850:INFO:main.cpp(70)] 3
*/
void fn_test()
{
// fn_test_bind_global_function();
fn_test_bind_class_member_function();
}
class cls_Ref : public base::RefCountedThreadSafe<cls_Ref> {
public:
cls_Ref() = default;
int Foo() { return 3; }
void PrintBye() { LOG(INFO) << "bye."; }
private:
friend class base::RefCountedThreadSafe<cls_Ref>;
virtual ~cls_Ref() = default;
DISALLOW_COPY_AND_ASSIGN(cls_Ref);
};
void fn_test_bind_class_member_function()
{
// 用base::Bind()绑定类
scoped_refptr<cls_Ref> p_cls_ref = new (cls_Ref);
// cls_Ref::Foo 的函数原型是 int(void)
base::Callback<int(void)> cb_cls_ref = base::Bind(&cls_Ref::Foo, p_cls_ref);
DLOG(WARNING) << ">> fn_test_bind_class_member_function()";
DLOG(INFO) << cb_cls_ref.Run(); // Prints out 3.
}
int Return5() { return 5; }
void fn_test_bind_global_function()
{
// 用base::Bind()绑定全局函数
base::Callback<int(void)> func_cb = base::Bind(&Return5);
DLOG(WARNING) << ">> fn_test_bind_global_function()";
LOG(INFO) << func_cb.Run(); // Prints 5.
DLOG(WARNING) << func_cb.Run();
}
Z:\chromium\src\base\test\BUILD.gn
# Trivial executable which outputs space-delimited argv to stdout,
# used for testing.
executable("test_child_process") {
testonly = true
sources = [
"test_child_process.cc",
]
deps = [
"//build/config:exe_and_shlib_deps",
]
}
executable("test_by_me") {
sources = [
"test_by_me/main.cpp",
]
deps = [
"//base",
]
}