wrote:
> Hello!
>
> The following code compiles with msvc-7.1, but gcc-3.4.4 fails. I fail
> too, in seeing why.
>
It doesn't compile on VC++8 or Comeau. Haven't tried it on 7.1.
You can get around it by doing the following:
>
> #include <iostream>
> #include <string>
> #include <stdexcept> // logic_error
>
> struct IgnoreErrorCode
> {};
>
> struct MandatoryErrorCodeException : public std::logic_error
> {
> MandatoryErrorCodeException(const char* s)
> : std::logic_error(s)
> { }
> };
>
> template<class CODE> class ErrorCode;
>
> template<class CODE>
> class ThrowableErrorCode
> {
> friend class ErrorCode<CODE>;
> CODE m_code;
> bool m_throw;
Make this "mutable":
mutable bool m_throw;
> public:
> //! constructor - receive the error code and arm the exception
> ThrowableErrorCode(CODE i_code)
> : m_code(i_code),
> m_throw(true)
> {}
>
> //! explicitly ignore the error code and avoid exception
> operator IgnoreErrorCode()
> {
> m_throw = false;
> return IgnoreErrorCode();
> }
> ~ThrowableErrorCode()
> {
> //! will throw unless ErrorCode<CODE> or IgnoreError will prevent
> it
> if( m_throw )
> throw MandatoryErrorCodeException("Must handle error code");
> }
> };
>
> template<class T>
> class ErrorCode
> {
> T m_code;
>
> public:
>
> ErrorCode(ThrowableErrorCode<T>& code)
And the parameter here const:
ErrorCode(const ThrowableErrorCode<T>& code)
> : m_code(code.m_code)
> {
> // prevent the throw
> code.m_throw = false;
> }
> operator T()
> {
> return this->m_code;
> }
> };
>
> ThrowableErrorCode<bool> CreateCode()
> {
> return false;
> }
>
> int main()
> {
> ErrorCode<bool> result = CreateCode();
>
> return 0;
> }
>
Just one possibility. You need to decide whether making m_throw a
mutable member is consistent with the way you have conceptualized your
solution.
Regards,
Sumit.