jumping656 / googlemock

Automatically exported from code.google.com/p/googlemock
BSD 3-Clause "New" or "Revised" License
0 stars 0 forks source link

Compile error if method signature contains type whose operator bool is not public #154

Open GoogleCodeExporter opened 9 years ago

GoogleCodeExporter commented 9 years ago
The following sample code leads to a compile error:

     5  class Result
     6  {
     7  public:
     8  private:
     9    operator bool() const { return false; }
    10  };
    11  
    12  class Database
    13  {
    14  public:
    15    virtual Result exec(const std::string& sql) = 0;
    16  };
    17  
    18  class MockDatabase : public Database
    19  {
    20  public:
    21    MOCK_METHOD1(exec,
    22      Result(const std::string& sql));
    23  };

The g++ compiler complains that the operator bool of the class Result is 
private:

main.cpp:9:3: Fehler: »Result::operator bool() const« is private
/usr/include/gtest/gtest-printers.h:169:42: error: in this context

That's a bug in my eyes. Is there a way to workaround this. The class Result
is part of 3rd party library such that I can't change it.

Regards, Hakan

Original issue reported on code.google.com by hyuek...@astaro.com on 29 Feb 2012 at 2:47

GoogleCodeExporter commented 9 years ago
Even if the issue has been discovered long time ago and it seems nobody else is 
interested. I discovered it now with VC2012 as well. I am using the following 
workaround:

- Create a wrapper for 3rd party class with private bool cast operator
- Implement the bool cast for the wrapper class
- Create a mock method with same signature but using the wrapper as 
return/parameter value
- Implement the method with the problem with original signature but calling
  the mocked method with wrapper
- Define expectations and stuff for mocked method with wrapper
- Add todo to remove when issue has been fixed

Original comment by s.lu...@gmail.com on 27 Jul 2015 at 6:43

GoogleCodeExporter commented 9 years ago
The simplest workaround is to provide a ostream<< operator in the namespace of 
Result:

namespace whatever {
ostream &operator<<(ostream &s, const Result &r) {
  return s << "Result";
}
}  // namespace whatever

It's always a little dangerous (ODR violations etc) to add stuff to other 
people's namespaces, but if you either add the above directly to the 
third-party include file, or alternatively in your own code making sure it is 
included everywhere the third-party include file is included, you should be ok.

Original comment by ko...@google.com on 7 Aug 2015 at 11:24