OSDN Git Service

#36897 [DTXC] MIDIインポート機能の呼び出し口を、ファイルメニュー内にも配置。
[dtxmania/dtxmania.git] / SlimDXc_Jun2010(VC++2008) / external / GMock / gmock / gmock-actions.h
1 // Copyright 2007, Google Inc.
2 // All rights reserved.
3 //
4 // Redistribution and use in source and binary forms, with or without
5 // modification, are permitted provided that the following conditions are
6 // met:
7 //
8 //     * Redistributions of source code must retain the above copyright
9 // notice, this list of conditions and the following disclaimer.
10 //     * Redistributions in binary form must reproduce the above
11 // copyright notice, this list of conditions and the following disclaimer
12 // in the documentation and/or other materials provided with the
13 // distribution.
14 //     * Neither the name of Google Inc. nor the names of its
15 // contributors may be used to endorse or promote products derived from
16 // this software without specific prior written permission.
17 //
18 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29 //
30 // Author: wan@google.com (Zhanyong Wan)
31
32 // Google Mock - a framework for writing C++ mock classes.
33 //
34 // This file implements some commonly used actions.
35
36 #ifndef GMOCK_INCLUDE_GMOCK_GMOCK_ACTIONS_H_
37 #define GMOCK_INCLUDE_GMOCK_GMOCK_ACTIONS_H_
38
39 #include <algorithm>
40 #include <string>
41
42 #ifndef _WIN32_WCE
43 #include <errno.h>
44 #endif
45
46 #include <gmock/internal/gmock-internal-utils.h>
47 #include <gmock/internal/gmock-port.h>
48
49 namespace testing {
50
51 // To implement an action Foo, define:
52 //   1. a class FooAction that implements the ActionInterface interface, and
53 //   2. a factory function that creates an Action object from a
54 //      const FooAction*.
55 //
56 // The two-level delegation design follows that of Matcher, providing
57 // consistency for extension developers.  It also eases ownership
58 // management as Action objects can now be copied like plain values.
59
60 namespace internal {
61
62 template <typename F>
63 class MonomorphicDoDefaultActionImpl;
64
65 template <typename F1, typename F2>
66 class ActionAdaptor;
67
68 // BuiltInDefaultValue<T>::Get() returns the "built-in" default
69 // value for type T, which is NULL when T is a pointer type, 0 when T
70 // is a numeric type, false when T is bool, or "" when T is string or
71 // std::string.  For any other type T, this value is undefined and the
72 // function will abort the process.
73 template <typename T>
74 class BuiltInDefaultValue {
75  public:
76   // This function returns true iff type T has a built-in default value.
77   static bool Exists() { return false; }
78   static T Get() {
79     Assert(false, __FILE__, __LINE__,
80            "Default action undefined for the function return type.");
81     return internal::Invalid<T>();
82     // The above statement will never be reached, but is required in
83     // order for this function to compile.
84   }
85 };
86
87 // This partial specialization says that we use the same built-in
88 // default value for T and const T.
89 template <typename T>
90 class BuiltInDefaultValue<const T> {
91  public:
92   static bool Exists() { return BuiltInDefaultValue<T>::Exists(); }
93   static T Get() { return BuiltInDefaultValue<T>::Get(); }
94 };
95
96 // This partial specialization defines the default values for pointer
97 // types.
98 template <typename T>
99 class BuiltInDefaultValue<T*> {
100  public:
101   static bool Exists() { return true; }
102   static T* Get() { return NULL; }
103 };
104
105 // The following specializations define the default values for
106 // specific types we care about.
107 #define GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(type, value) \
108   template <> \
109   class BuiltInDefaultValue<type> { \
110    public: \
111     static bool Exists() { return true; } \
112     static type Get() { return value; } \
113   }
114
115 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(void, );  // NOLINT
116 #if GTEST_HAS_GLOBAL_STRING
117 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(::string, "");
118 #endif  // GTEST_HAS_GLOBAL_STRING
119 #if GTEST_HAS_STD_STRING
120 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(::std::string, "");
121 #endif  // GTEST_HAS_STD_STRING
122 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(bool, false);
123 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned char, '\0');
124 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed char, '\0');
125 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(char, '\0');
126
127 // signed wchar_t and unsigned wchar_t are NOT in the C++ standard.
128 // Using them is a bad practice and not portable.  So don't use them.
129 //
130 // Still, Google Mock is designed to work even if the user uses signed
131 // wchar_t or unsigned wchar_t (obviously, assuming the compiler
132 // supports them).
133 //
134 // To gcc,
135 //
136 //   wchar_t == signed wchar_t != unsigned wchar_t == unsigned int
137 //
138 // MSVC does not recognize signed wchar_t or unsigned wchar_t.  It
139 // treats wchar_t as a native type usually, but treats it as the same
140 // as unsigned short when the compiler option /Zc:wchar_t- is
141 // specified.
142 //
143 // Therefore we provide a default action for wchar_t when compiled
144 // with gcc or _NATIVE_WCHAR_T_DEFINED is defined.
145 //
146 // There's no need for a default action for signed wchar_t, as that
147 // type is the same as wchar_t for gcc, and invalid for MSVC.
148 //
149 // There's also no need for a default action for unsigned wchar_t, as
150 // that type is the same as unsigned int for gcc, and invalid for
151 // MSVC.
152 #if defined(__GNUC__) || defined(_NATIVE_WCHAR_T_DEFINED)
153 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(wchar_t, 0U);  // NOLINT
154 #endif
155
156 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned short, 0U);  // NOLINT
157 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed short, 0);     // NOLINT
158 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned int, 0U);
159 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed int, 0);
160 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned long, 0UL);  // NOLINT
161 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed long, 0L);     // NOLINT
162 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(UInt64, 0);
163 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(Int64, 0);
164 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(float, 0);
165 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(double, 0);
166
167 #undef GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_
168
169 }  // namespace internal
170
171 // When an unexpected function call is encountered, Google Mock will
172 // let it return a default value if the user has specified one for its
173 // return type, or if the return type has a built-in default value;
174 // otherwise Google Mock won't know what value to return and will have
175 // to abort the process.
176 //
177 // The DefaultValue<T> class allows a user to specify the
178 // default value for a type T that is both copyable and publicly
179 // destructible (i.e. anything that can be used as a function return
180 // type).  The usage is:
181 //
182 //   // Sets the default value for type T to be foo.
183 //   DefaultValue<T>::Set(foo);
184 template <typename T>
185 class DefaultValue {
186  public:
187   // Sets the default value for type T; requires T to be
188   // copy-constructable and have a public destructor.
189   static void Set(T x) {
190     delete value_;
191     value_ = new T(x);
192   }
193
194   // Unsets the default value for type T.
195   static void Clear() {
196     delete value_;
197     value_ = NULL;
198   }
199
200   // Returns true iff the user has set the default value for type T.
201   static bool IsSet() { return value_ != NULL; }
202
203   // Returns true if T has a default return value set by the user or there
204   // exists a built-in default value.
205   static bool Exists() {
206     return IsSet() || internal::BuiltInDefaultValue<T>::Exists();
207   }
208
209   // Returns the default value for type T if the user has set one;
210   // otherwise returns the built-in default value if there is one;
211   // otherwise aborts the process.
212   static T Get() {
213     return value_ == NULL ?
214         internal::BuiltInDefaultValue<T>::Get() : *value_;
215   }
216  private:
217   static const T* value_;
218 };
219
220 // This partial specialization allows a user to set default values for
221 // reference types.
222 template <typename T>
223 class DefaultValue<T&> {
224  public:
225   // Sets the default value for type T&.
226   static void Set(T& x) {  // NOLINT
227     address_ = &x;
228   }
229
230   // Unsets the default value for type T&.
231   static void Clear() {
232     address_ = NULL;
233   }
234
235   // Returns true iff the user has set the default value for type T&.
236   static bool IsSet() { return address_ != NULL; }
237
238   // Returns true if T has a default return value set by the user or there
239   // exists a built-in default value.
240   static bool Exists() {
241     return IsSet() || internal::BuiltInDefaultValue<T&>::Exists();
242   }
243
244   // Returns the default value for type T& if the user has set one;
245   // otherwise returns the built-in default value if there is one;
246   // otherwise aborts the process.
247   static T& Get() {
248     return address_ == NULL ?
249         internal::BuiltInDefaultValue<T&>::Get() : *address_;
250   }
251  private:
252   static T* address_;
253 };
254
255 // This specialization allows DefaultValue<void>::Get() to
256 // compile.
257 template <>
258 class DefaultValue<void> {
259  public:
260   static bool Exists() { return true; }
261   static void Get() {}
262 };
263
264 // Points to the user-set default value for type T.
265 template <typename T>
266 const T* DefaultValue<T>::value_ = NULL;
267
268 // Points to the user-set default value for type T&.
269 template <typename T>
270 T* DefaultValue<T&>::address_ = NULL;
271
272 // Implement this interface to define an action for function type F.
273 template <typename F>
274 class ActionInterface {
275  public:
276   typedef typename internal::Function<F>::Result Result;
277   typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;
278
279   ActionInterface() : is_do_default_(false) {}
280
281   virtual ~ActionInterface() {}
282
283   // Performs the action.  This method is not const, as in general an
284   // action can have side effects and be stateful.  For example, a
285   // get-the-next-element-from-the-collection action will need to
286   // remember the current element.
287   virtual Result Perform(const ArgumentTuple& args) = 0;
288
289   // Returns true iff this is the DoDefault() action.
290   bool IsDoDefault() const { return is_do_default_; }
291  private:
292   template <typename Function>
293   friend class internal::MonomorphicDoDefaultActionImpl;
294
295   // This private constructor is reserved for implementing
296   // DoDefault(), the default action for a given mock function.
297   explicit ActionInterface(bool is_do_default)
298       : is_do_default_(is_do_default) {}
299
300   // True iff this action is DoDefault().
301   const bool is_do_default_;
302 };
303
304 // An Action<F> is a copyable and IMMUTABLE (except by assignment)
305 // object that represents an action to be taken when a mock function
306 // of type F is called.  The implementation of Action<T> is just a
307 // linked_ptr to const ActionInterface<T>, so copying is fairly cheap.
308 // Don't inherit from Action!
309 //
310 // You can view an object implementing ActionInterface<F> as a
311 // concrete action (including its current state), and an Action<F>
312 // object as a handle to it.
313 template <typename F>
314 class Action {
315  public:
316   typedef typename internal::Function<F>::Result Result;
317   typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;
318
319   // Constructs a null Action.  Needed for storing Action objects in
320   // STL containers.
321   Action() : impl_(NULL) {}
322
323   // Constructs an Action from its implementation.
324   explicit Action(ActionInterface<F>* impl) : impl_(impl) {}
325
326   // Copy constructor.
327   Action(const Action& action) : impl_(action.impl_) {}
328
329   // This constructor allows us to turn an Action<Func> object into an
330   // Action<F>, as long as F's arguments can be implicitly converted
331   // to Func's and Func's return type cann be implicitly converted to
332   // F's.
333   template <typename Func>
334   explicit Action(const Action<Func>& action);
335
336   // Returns true iff this is the DoDefault() action.
337   bool IsDoDefault() const { return impl_->IsDoDefault(); }
338
339   // Performs the action.  Note that this method is const even though
340   // the corresponding method in ActionInterface is not.  The reason
341   // is that a const Action<F> means that it cannot be re-bound to
342   // another concrete action, not that the concrete action it binds to
343   // cannot change state.  (Think of the difference between a const
344   // pointer and a pointer to const.)
345   Result Perform(const ArgumentTuple& args) const {
346     return impl_->Perform(args);
347   }
348  private:
349   template <typename F1, typename F2>
350   friend class internal::ActionAdaptor;
351
352   internal::linked_ptr<ActionInterface<F> > impl_;
353 };
354
355 // The PolymorphicAction class template makes it easy to implement a
356 // polymorphic action (i.e. an action that can be used in mock
357 // functions of than one type, e.g. Return()).
358 //
359 // To define a polymorphic action, a user first provides a COPYABLE
360 // implementation class that has a Perform() method template:
361 //
362 //   class FooAction {
363 //    public:
364 //     template <typename Result, typename ArgumentTuple>
365 //     Result Perform(const ArgumentTuple& args) const {
366 //       // Processes the arguments and returns a result, using
367 //       // tr1::get<N>(args) to get the N-th (0-based) argument in the tuple.
368 //     }
369 //     ...
370 //   };
371 //
372 // Then the user creates the polymorphic action using
373 // MakePolymorphicAction(object) where object has type FooAction.  See
374 // the definition of Return(void) and SetArgumentPointee<N>(value) for
375 // complete examples.
376 template <typename Impl>
377 class PolymorphicAction {
378  public:
379   explicit PolymorphicAction(const Impl& impl) : impl_(impl) {}
380
381   template <typename F>
382   operator Action<F>() const {
383     return Action<F>(new MonomorphicImpl<F>(impl_));
384   }
385  private:
386   template <typename F>
387   class MonomorphicImpl : public ActionInterface<F> {
388    public:
389     typedef typename internal::Function<F>::Result Result;
390     typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;
391
392     explicit MonomorphicImpl(const Impl& impl) : impl_(impl) {}
393
394     virtual Result Perform(const ArgumentTuple& args) {
395       return impl_.template Perform<Result>(args);
396     }
397
398    private:
399     Impl impl_;
400   };
401
402   Impl impl_;
403 };
404
405 // Creates an Action from its implementation and returns it.  The
406 // created Action object owns the implementation.
407 template <typename F>
408 Action<F> MakeAction(ActionInterface<F>* impl) {
409   return Action<F>(impl);
410 }
411
412 // Creates a polymorphic action from its implementation.  This is
413 // easier to use than the PolymorphicAction<Impl> constructor as it
414 // doesn't require you to explicitly write the template argument, e.g.
415 //
416 //   MakePolymorphicAction(foo);
417 // vs
418 //   PolymorphicAction<TypeOfFoo>(foo);
419 template <typename Impl>
420 inline PolymorphicAction<Impl> MakePolymorphicAction(const Impl& impl) {
421   return PolymorphicAction<Impl>(impl);
422 }
423
424 namespace internal {
425
426 // Allows an Action<F2> object to pose as an Action<F1>, as long as F2
427 // and F1 are compatible.
428 template <typename F1, typename F2>
429 class ActionAdaptor : public ActionInterface<F1> {
430  public:
431   typedef typename internal::Function<F1>::Result Result;
432   typedef typename internal::Function<F1>::ArgumentTuple ArgumentTuple;
433
434   explicit ActionAdaptor(const Action<F2>& from) : impl_(from.impl_) {}
435
436   virtual Result Perform(const ArgumentTuple& args) {
437     return impl_->Perform(args);
438   }
439  private:
440   const internal::linked_ptr<ActionInterface<F2> > impl_;
441 };
442
443 // Implements the polymorphic Return(x) action, which can be used in
444 // any function that returns the type of x, regardless of the argument
445 // types.
446 template <typename R>
447 class ReturnAction {
448  public:
449   // Constructs a ReturnAction object from the value to be returned.
450   // 'value' is passed by value instead of by const reference in order
451   // to allow Return("string literal") to compile.
452   explicit ReturnAction(R value) : value_(value) {}
453
454   // This template type conversion operator allows Return(x) to be
455   // used in ANY function that returns x's type.
456   template <typename F>
457   operator Action<F>() const {
458     // Assert statement belongs here because this is the best place to verify
459     // conditions on F. It produces the clearest error messages
460     // in most compilers.
461     // Impl really belongs in this scope as a local class but can't
462     // because MSVC produces duplicate symbols in different translation units
463     // in this case. Until MS fixes that bug we put Impl into the class scope
464     // and put the typedef both here (for use in assert statement) and
465     // in the Impl class. But both definitions must be the same.
466     typedef typename Function<F>::Result Result;
467     GMOCK_COMPILE_ASSERT_(
468         !internal::is_reference<Result>::value,
469         use_ReturnRef_instead_of_Return_to_return_a_reference);
470     return Action<F>(new Impl<F>(value_));
471   }
472  private:
473   // Implements the Return(x) action for a particular function type F.
474   template <typename F>
475   class Impl : public ActionInterface<F> {
476    public:
477     typedef typename Function<F>::Result Result;
478     typedef typename Function<F>::ArgumentTuple ArgumentTuple;
479
480     explicit Impl(R value) : value_(value) {}
481
482     virtual Result Perform(const ArgumentTuple&) { return value_; }
483
484    private:
485     R value_;
486   };
487
488   R value_;
489 };
490
491 // Implements the ReturnNull() action.
492 class ReturnNullAction {
493  public:
494   // Allows ReturnNull() to be used in any pointer-returning function.
495   template <typename Result, typename ArgumentTuple>
496   static Result Perform(const ArgumentTuple&) {
497     GMOCK_COMPILE_ASSERT_(internal::is_pointer<Result>::value,
498                           ReturnNull_can_be_used_to_return_a_pointer_only);
499     return NULL;
500   }
501 };
502
503 // Implements the Return() action.
504 class ReturnVoidAction {
505  public:
506   // Allows Return() to be used in any void-returning function.
507   template <typename Result, typename ArgumentTuple>
508   static void Perform(const ArgumentTuple&) {
509     CompileAssertTypesEqual<void, Result>();
510   }
511 };
512
513 // Implements the polymorphic ReturnRef(x) action, which can be used
514 // in any function that returns a reference to the type of x,
515 // regardless of the argument types.
516 template <typename T>
517 class ReturnRefAction {
518  public:
519   // Constructs a ReturnRefAction object from the reference to be returned.
520   explicit ReturnRefAction(T& ref) : ref_(ref) {}  // NOLINT
521
522   // This template type conversion operator allows ReturnRef(x) to be
523   // used in ANY function that returns a reference to x's type.
524   template <typename F>
525   operator Action<F>() const {
526     typedef typename Function<F>::Result Result;
527     // Asserts that the function return type is a reference.  This
528     // catches the user error of using ReturnRef(x) when Return(x)
529     // should be used, and generates some helpful error message.
530     GMOCK_COMPILE_ASSERT_(internal::is_reference<Result>::value,
531                           use_Return_instead_of_ReturnRef_to_return_a_value);
532     return Action<F>(new Impl<F>(ref_));
533   }
534  private:
535   // Implements the ReturnRef(x) action for a particular function type F.
536   template <typename F>
537   class Impl : public ActionInterface<F> {
538    public:
539     typedef typename Function<F>::Result Result;
540     typedef typename Function<F>::ArgumentTuple ArgumentTuple;
541
542     explicit Impl(T& ref) : ref_(ref) {}  // NOLINT
543
544     virtual Result Perform(const ArgumentTuple&) {
545       return ref_;
546     }
547    private:
548     T& ref_;
549   };
550
551   T& ref_;
552 };
553
554 // Implements the DoDefault() action for a particular function type F.
555 template <typename F>
556 class MonomorphicDoDefaultActionImpl : public ActionInterface<F> {
557  public:
558   typedef typename Function<F>::Result Result;
559   typedef typename Function<F>::ArgumentTuple ArgumentTuple;
560
561   MonomorphicDoDefaultActionImpl() : ActionInterface<F>(true) {}
562
563   // For technical reasons, DoDefault() cannot be used inside a
564   // composite action (e.g. DoAll(...)).  It can only be used at the
565   // top level in an EXPECT_CALL().  If this function is called, the
566   // user must be using DoDefault() inside a composite action, and we
567   // have to generate a run-time error.
568   virtual Result Perform(const ArgumentTuple&) {
569     Assert(false, __FILE__, __LINE__,
570            "You are using DoDefault() inside a composite action like "
571            "DoAll() or WithArgs().  This is not supported for technical "
572            "reasons.  Please instead spell out the default action, or "
573            "assign the default action to an Action variable and use "
574            "the variable in various places.");
575     return internal::Invalid<Result>();
576     // The above statement will never be reached, but is required in
577     // order for this function to compile.
578   }
579 };
580
581 // Implements the polymorphic DoDefault() action.
582 class DoDefaultAction {
583  public:
584   // This template type conversion operator allows DoDefault() to be
585   // used in any function.
586   template <typename F>
587   operator Action<F>() const {
588     return Action<F>(new MonomorphicDoDefaultActionImpl<F>);
589   }
590 };
591
592 // Implements the Assign action to set a given pointer referent to a
593 // particular value.
594 template <typename T1, typename T2>
595 class AssignAction {
596  public:
597   AssignAction(T1* ptr, T2 value) : ptr_(ptr), value_(value) {}
598
599   template <typename Result, typename ArgumentTuple>
600   void Perform(const ArgumentTuple& /* args */) const {
601     *ptr_ = value_;
602   }
603  private:
604   T1* const ptr_;
605   const T2 value_;
606 };
607
608 #ifndef _WIN32_WCE
609
610 // Implements the SetErrnoAndReturn action to simulate return from
611 // various system calls and libc functions.
612 template <typename T>
613 class SetErrnoAndReturnAction {
614  public:
615   SetErrnoAndReturnAction(int errno_value, T result)
616       : errno_(errno_value),
617         result_(result) {}
618   template <typename Result, typename ArgumentTuple>
619   Result Perform(const ArgumentTuple& /* args */) const {
620     errno = errno_;
621     return result_;
622   }
623  private:
624   const int errno_;
625   const T result_;
626 };
627
628 #endif  // _WIN32_WCE
629
630 // Implements the SetArgumentPointee<N>(x) action for any function
631 // whose N-th argument (0-based) is a pointer to x's type.  The
632 // template parameter kIsProto is true iff type A is ProtocolMessage,
633 // proto2::Message, or a sub-class of those.
634 template <size_t N, typename A, bool kIsProto>
635 class SetArgumentPointeeAction {
636  public:
637   // Constructs an action that sets the variable pointed to by the
638   // N-th function argument to 'value'.
639   explicit SetArgumentPointeeAction(const A& value) : value_(value) {}
640
641   template <typename Result, typename ArgumentTuple>
642   void Perform(const ArgumentTuple& args) const {
643     CompileAssertTypesEqual<void, Result>();
644     *::std::tr1::get<N>(args) = value_;
645   }
646
647  private:
648   const A value_;
649 };
650
651 template <size_t N, typename Proto>
652 class SetArgumentPointeeAction<N, Proto, true> {
653  public:
654   // Constructs an action that sets the variable pointed to by the
655   // N-th function argument to 'proto'.  Both ProtocolMessage and
656   // proto2::Message have the CopyFrom() method, so the same
657   // implementation works for both.
658   explicit SetArgumentPointeeAction(const Proto& proto) : proto_(new Proto) {
659     proto_->CopyFrom(proto);
660   }
661
662   template <typename Result, typename ArgumentTuple>
663   void Perform(const ArgumentTuple& args) const {
664     CompileAssertTypesEqual<void, Result>();
665     ::std::tr1::get<N>(args)->CopyFrom(*proto_);
666   }
667  private:
668   const internal::linked_ptr<Proto> proto_;
669 };
670
671 // Implements the SetArrayArgument<N>(first, last) action for any function
672 // whose N-th argument (0-based) is a pointer or iterator to a type that can be
673 // implicitly converted from *first.
674 template <size_t N, typename InputIterator>
675 class SetArrayArgumentAction {
676  public:
677   // Constructs an action that sets the variable pointed to by the
678   // N-th function argument to 'value'.
679   explicit SetArrayArgumentAction(InputIterator first, InputIterator last)
680       : first_(first), last_(last) {
681   }
682
683   template <typename Result, typename ArgumentTuple>
684   void Perform(const ArgumentTuple& args) const {
685     CompileAssertTypesEqual<void, Result>();
686
687     // Microsoft compiler deprecates ::std::copy, so we want to suppress warning
688     // 4996 (Function call with parameters that may be unsafe) there.
689 #if GTEST_OS_WINDOWS
690 #pragma warning(push)          // Saves the current warning state.
691 #pragma warning(disable:4996)  // Temporarily disables warning 4996.
692 #endif  // GTEST_OS_WINDOWS
693     ::std::copy(first_, last_, ::std::tr1::get<N>(args));
694 #if GTEST_OS_WINDOWS
695 #pragma warning(pop)           // Restores the warning state.
696 #endif  // GTEST_OS_WINDOWS
697   }
698
699  private:
700   const InputIterator first_;
701   const InputIterator last_;
702 };
703
704 // Implements the InvokeWithoutArgs(f) action.  The template argument
705 // FunctionImpl is the implementation type of f, which can be either a
706 // function pointer or a functor.  InvokeWithoutArgs(f) can be used as an
707 // Action<F> as long as f's type is compatible with F (i.e. f can be
708 // assigned to a tr1::function<F>).
709 template <typename FunctionImpl>
710 class InvokeWithoutArgsAction {
711  public:
712   // The c'tor makes a copy of function_impl (either a function
713   // pointer or a functor).
714   explicit InvokeWithoutArgsAction(FunctionImpl function_impl)
715       : function_impl_(function_impl) {}
716
717   // Allows InvokeWithoutArgs(f) to be used as any action whose type is
718   // compatible with f.
719   template <typename Result, typename ArgumentTuple>
720   Result Perform(const ArgumentTuple&) { return function_impl_(); }
721  private:
722   FunctionImpl function_impl_;
723 };
724
725 // Implements the InvokeWithoutArgs(object_ptr, &Class::Method) action.
726 template <class Class, typename MethodPtr>
727 class InvokeMethodWithoutArgsAction {
728  public:
729   InvokeMethodWithoutArgsAction(Class* obj_ptr, MethodPtr method_ptr)
730       : obj_ptr_(obj_ptr), method_ptr_(method_ptr) {}
731
732   template <typename Result, typename ArgumentTuple>
733   Result Perform(const ArgumentTuple&) const {
734     return (obj_ptr_->*method_ptr_)();
735   }
736  private:
737   Class* const obj_ptr_;
738   const MethodPtr method_ptr_;
739 };
740
741 // Implements the IgnoreResult(action) action.
742 template <typename A>
743 class IgnoreResultAction {
744  public:
745   explicit IgnoreResultAction(const A& action) : action_(action) {}
746
747   template <typename F>
748   operator Action<F>() const {
749     // Assert statement belongs here because this is the best place to verify
750     // conditions on F. It produces the clearest error messages
751     // in most compilers.
752     // Impl really belongs in this scope as a local class but can't
753     // because MSVC produces duplicate symbols in different translation units
754     // in this case. Until MS fixes that bug we put Impl into the class scope
755     // and put the typedef both here (for use in assert statement) and
756     // in the Impl class. But both definitions must be the same.
757     typedef typename internal::Function<F>::Result Result;
758
759     // Asserts at compile time that F returns void.
760     CompileAssertTypesEqual<void, Result>();
761
762     return Action<F>(new Impl<F>(action_));
763   }
764  private:
765   template <typename F>
766   class Impl : public ActionInterface<F> {
767    public:
768     typedef typename internal::Function<F>::Result Result;
769     typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;
770
771     explicit Impl(const A& action) : action_(action) {}
772
773     virtual void Perform(const ArgumentTuple& args) {
774       // Performs the action and ignores its result.
775       action_.Perform(args);
776     }
777
778    private:
779     // Type OriginalFunction is the same as F except that its return
780     // type is IgnoredValue.
781     typedef typename internal::Function<F>::MakeResultIgnoredValue
782         OriginalFunction;
783
784     const Action<OriginalFunction> action_;
785   };
786
787   const A action_;
788 };
789
790 }  // namespace internal
791
792 // An Unused object can be implicitly constructed from ANY value.
793 // This is handy when defining actions that ignore some or all of the
794 // mock function arguments.  For example, given
795 //
796 //   MOCK_METHOD3(Foo, double(const string& label, double x, double y));
797 //   MOCK_METHOD3(Bar, double(int index, double x, double y));
798 //
799 // instead of
800 //
801 //   double DistanceToOriginWithLabel(const string& label, double x, double y) {
802 //     return sqrt(x*x + y*y);
803 //   }
804 //   double DistanceToOriginWithIndex(int index, double x, double y) {
805 //     return sqrt(x*x + y*y);
806 //   }
807 //   ...
808 //   EXEPCT_CALL(mock, Foo("abc", _, _))
809 //       .WillOnce(Invoke(DistanceToOriginWithLabel));
810 //   EXEPCT_CALL(mock, Bar(5, _, _))
811 //       .WillOnce(Invoke(DistanceToOriginWithIndex));
812 //
813 // you could write
814 //
815 //   // We can declare any uninteresting argument as Unused.
816 //   double DistanceToOrigin(Unused, double x, double y) {
817 //     return sqrt(x*x + y*y);
818 //   }
819 //   ...
820 //   EXEPCT_CALL(mock, Foo("abc", _, _)).WillOnce(Invoke(DistanceToOrigin));
821 //   EXEPCT_CALL(mock, Bar(5, _, _)).WillOnce(Invoke(DistanceToOrigin));
822 typedef internal::IgnoredValue Unused;
823
824 // This constructor allows us to turn an Action<From> object into an
825 // Action<To>, as long as To's arguments can be implicitly converted
826 // to From's and From's return type cann be implicitly converted to
827 // To's.
828 template <typename To>
829 template <typename From>
830 Action<To>::Action(const Action<From>& from)
831     : impl_(new internal::ActionAdaptor<To, From>(from)) {}
832
833 // Creates an action that returns 'value'.  'value' is passed by value
834 // instead of const reference - otherwise Return("string literal")
835 // will trigger a compiler error about using array as initializer.
836 template <typename R>
837 internal::ReturnAction<R> Return(R value) {
838   return internal::ReturnAction<R>(value);
839 }
840
841 // Creates an action that returns NULL.
842 inline PolymorphicAction<internal::ReturnNullAction> ReturnNull() {
843   return MakePolymorphicAction(internal::ReturnNullAction());
844 }
845
846 // Creates an action that returns from a void function.
847 inline PolymorphicAction<internal::ReturnVoidAction> Return() {
848   return MakePolymorphicAction(internal::ReturnVoidAction());
849 }
850
851 // Creates an action that returns the reference to a variable.
852 template <typename R>
853 inline internal::ReturnRefAction<R> ReturnRef(R& x) {  // NOLINT
854   return internal::ReturnRefAction<R>(x);
855 }
856
857 // Creates an action that does the default action for the give mock function.
858 inline internal::DoDefaultAction DoDefault() {
859   return internal::DoDefaultAction();
860 }
861
862 // Creates an action that sets the variable pointed by the N-th
863 // (0-based) function argument to 'value'.
864 template <size_t N, typename T>
865 PolymorphicAction<
866   internal::SetArgumentPointeeAction<
867     N, T, internal::IsAProtocolMessage<T>::value> >
868 SetArgumentPointee(const T& x) {
869   return MakePolymorphicAction(internal::SetArgumentPointeeAction<
870       N, T, internal::IsAProtocolMessage<T>::value>(x));
871 }
872
873 // Creates an action that sets the elements of the array pointed to by the N-th
874 // (0-based) function argument, which can be either a pointer or an iterator,
875 // to the values of the elements in the source range [first, last).
876 template <size_t N, typename InputIterator>
877 PolymorphicAction<internal::SetArrayArgumentAction<N, InputIterator> >
878 SetArrayArgument(InputIterator first, InputIterator last) {
879   return MakePolymorphicAction(internal::SetArrayArgumentAction<
880       N, InputIterator>(first, last));
881 }
882
883 // Creates an action that sets a pointer referent to a given value.
884 template <typename T1, typename T2>
885 PolymorphicAction<internal::AssignAction<T1, T2> > Assign(T1* ptr, T2 val) {
886   return MakePolymorphicAction(internal::AssignAction<T1, T2>(ptr, val));
887 }
888
889 #ifndef _WIN32_WCE
890
891 // Creates an action that sets errno and returns the appropriate error.
892 template <typename T>
893 PolymorphicAction<internal::SetErrnoAndReturnAction<T> >
894 SetErrnoAndReturn(int errval, T result) {
895   return MakePolymorphicAction(
896       internal::SetErrnoAndReturnAction<T>(errval, result));
897 }
898
899 #endif  // _WIN32_WCE
900
901 // Various overloads for InvokeWithoutArgs().
902
903 // Creates an action that invokes 'function_impl' with no argument.
904 template <typename FunctionImpl>
905 PolymorphicAction<internal::InvokeWithoutArgsAction<FunctionImpl> >
906 InvokeWithoutArgs(FunctionImpl function_impl) {
907   return MakePolymorphicAction(
908       internal::InvokeWithoutArgsAction<FunctionImpl>(function_impl));
909 }
910
911 // Creates an action that invokes the given method on the given object
912 // with no argument.
913 template <class Class, typename MethodPtr>
914 PolymorphicAction<internal::InvokeMethodWithoutArgsAction<Class, MethodPtr> >
915 InvokeWithoutArgs(Class* obj_ptr, MethodPtr method_ptr) {
916   return MakePolymorphicAction(
917       internal::InvokeMethodWithoutArgsAction<Class, MethodPtr>(
918           obj_ptr, method_ptr));
919 }
920
921 // Creates an action that performs an_action and throws away its
922 // result.  In other words, it changes the return type of an_action to
923 // void.  an_action MUST NOT return void, or the code won't compile.
924 template <typename A>
925 inline internal::IgnoreResultAction<A> IgnoreResult(const A& an_action) {
926   return internal::IgnoreResultAction<A>(an_action);
927 }
928
929 }  // namespace testing
930
931 #endif  // GMOCK_INCLUDE_GMOCK_GMOCK_ACTIONS_H_