将错误代码枚举与std::error_code进行比较

10
我正在使用C++11的system_error错误代码库为我创建的一个库创建自定义错误类。我之前已经使用过boost::error_code,但是我无法让std::error_code正常工作。我正在使用GCC 4.6。
基本上,我已经编写了所有的样板代码来创建一个错误类,一个错误类型以及STD命名空间中的转换函数,将我的自定义枚举转换为std::error_code对象:
namespace mylib
{
    namespace errc {

        enum my_error
        {
            failed = 0
        };

        inline const char* error_message(int c)
        {
            static const char* err_msg[] = 
            {
                "Failed",
            };

            assert(c < sizeof(err_msg) / sizeof(err_msg[0]));
            return err_msg[c];
        }

        class my_error_category : public std::error_category
        {
            public:

            my_error_category()
            { }

            std::string message(int c) const
            { 
                return error_message(c); 
            }

            const char* name() const { return "My Error Category"; }

            const static error_category& get()
            {
                const static my_error_category category_const;
                return category_const;
            }
        };

    } // end namespace errc
} // end namespace mylib

namespace std {

inline error_code make_error_code(mylib::errc::my_error e)
{
    return error_code(static_cast<int>(e), mylib::errc::my_error_category::get());
}

template<>
struct is_error_code_enum<mylib::errc::my_error>
    : std::true_type
{ }; 

问题是,我的错误码枚举类型和 std::error_code 对象之间的隐式转换似乎不起作用,因此我无法比较 std::error_code 实例和枚举字面量。
int main()
{
    std::error_code ec1 = std::make_error_code(mylib::errc::failed); // works
    std::error_code ec2 = mylib::errc::failed; // doesn't compile
    bool result = (ec2 == mylib::errc::failed); // doesn't compile
}

表达式ec2 == mylib::errc::failed无法编译 - 我必须使用ec2 == std::make_error_code(mylib::errc::failed)

编译器发出的错误信息是:

In file included from test6.cc:3:0:
/usr/include/c++/4.6/system_error: In constructor ‘std::error_code::error_code(_ErrorCodeEnum, typename std::enable_if<std::is_error_code_enum<_ErrorCodeEnum>::value>::type*) [with _ErrorCodeEnum = mylib::errc::my_error, typename std::enable_if<std::is_error_code_enum<_ErrorCodeEnum>::value>::type = void]’:
test6.cc:70:37:   instantiated from here
/usr/include/c++/4.6/system_error:127:9: error: cannot convert ‘mylib::errc::my_error’ to ‘std::errc’ for argument ‘1’ to ‘std::error_code std::make_error_code(std::errc)’

这里是一个Ideone链接

那么,为什么这不起作用呢?我需要额外的样板代码来使mylib::errc::my_error枚举隐式转换为std::error_code吗?我认为std::make_error_code的特化已经解决了这个问题?

1个回答

9

你需要将error_code make_error_code(mylib::errc::my_error e)函数从std移动到你的错误命名空间(mylib::errc)。请参考http://ideone.com/eSfee


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接