chromium之tuple
// A Tuple is a generic templatized container, similar in concept to std::pair. // There are classes Tuple0 to Tuple6, cooresponding to the number of elements // it contains. The convenient MakeTuple() function takes 0 to 6 arguments, // and will construct and return the appropriate Tuple object. The functions // DispatchToMethod and DispatchToFunction take a function pointer or instance // and method pointer, and unpack a tuple into arguments to the call. // // Tuple elements are copied by value, and stored in the tuple. See the unit // tests for more details of how/when the values are copied. // // Example usage: // // These two methods of creating a Tuple are identical. // Tuple2<int, const char*> tuple_a(1, "wee"); // Tuple2<int, const char*> tuple_b = MakeTuple(1, "wee"); // // void SomeFunc(int a, const char* b) { } // DispatchToFunction(&SomeFunc, tuple_a); // SomeFunc(1, "wee") // DispatchToFunction( // &SomeFunc, MakeTuple(10, "foo")); // SomeFunc(10, "foo") // // struct { void SomeMeth(int a, int b, int c) { } } foo; // DispatchToMethod(&foo, &Foo::SomeMeth, MakeTuple(1, 2, 3)); // // foo->SomeMeth(1, 2, 3);
Tuple是一个通用的模板化容器,类似std::pair的概念。
转换函数MakeTuple接收0-6个参数,并返回一个Tuple对象
DispatchToFunction 接收一个函数指针,并解压一个tuple作为函数指针的参数,并调用
// void SomeFunc(int a, const char* b) { } // DispatchToFunction(&SomeFunc, tuple_a); // SomeFunc(1, "wee")
DispatchToMethod 接收一个实例、实例的方法指针,并解压一个tuple作为函数指针的参数,并调用
// struct { void SomeMeth(int a, int b, int c) { } } foo; // DispatchToMethod(&foo, &Foo::SomeMeth, MakeTuple(1, 2, 3));
看看代码
template <class P> struct TupleTraits { typedef P ValueType; typedef P& RefType; typedef const P& ParamType; }; template <class P> struct TupleTraits<P&> { typedef P ValueType; typedef P& RefType; typedef P& ParamType; }; template <class A> struct Tuple1 { public: typedef A TypeA; typedef Tuple1<typename TupleTraits<A>::ValueType> ValueTuple; typedef Tuple1<typename TupleTraits<A>::RefType> RefTuple; typedef Tuple1<typename TupleTraits<A>::ParamType> ParamTuple; Tuple1() {} explicit Tuple1(typename TupleTraits<A>::ParamType a) : a(a) {} A a; }; template <class Function, class A> inline void DispatchToFunction(Function function, const Tuple1<A>& arg) { (*function)(arg.a); }