D
dlidstrom
Hello!
The following code compiles with msvc-7.1, but gcc-3.4.4 fails. I fail
too, in seeing why.
#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;
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)
: 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;
}
gcc says this:
main.cpp: In function `int main()':
main.cpp:71: error: conversion from `ThrowableErrorCode<bool>' to
non-scalar type `ErrorCode<bool>' requested
What is wrong with the constructor in ErrorCode?
The following code compiles with msvc-7.1, but gcc-3.4.4 fails. I fail
too, in seeing why.
#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;
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)
: 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;
}
gcc says this:
main.cpp: In function `int main()':
main.cpp:71: error: conversion from `ThrowableErrorCode<bool>' to
non-scalar type `ErrorCode<bool>' requested
What is wrong with the constructor in ErrorCode?