2017-08-24 36 views
0

我是still通過std :: error_code,現在我試圖讓我的列表錯誤枚舉相當於std :: error_code。我正在關注this教程上的內容,但由於某些原因,我無法使其工作,所以我總是以錯誤No viable conversion from 'my_project::my_error' to 'std::error_code'結尾。試圖讓我的枚舉相當於std :: error_code

這就是我的工作:

#include <system_error> 
#include <string> 

namespace std { 

    enum class my_error; 

    template <> 
    struct is_error_condition_enum<my_error> : public true_type {}; 
} 

namespace my_project { 
    enum class my_error { 
    warning = 45836431 
    }; 

    namespace internal { 
    struct my_error_category : public std::error_category { 
     const char* name() const noexcept override { 
     return "AAA"; 
     } 
     std::string message(int ev) const noexcept override { 
     const std::string message = "BBB"; 
     return message; 
     } 
    }; 
    } 
} 

inline std::error_code make_error_code(const my_project::my_error &e) { 
    return {static_cast<int>(e), my_project::internal::my_error_category()}; 
}; 

int main() 
{ 
    std::error_code ec = my_project::my_error::warning; 
} 
+0

你寫了'make_error_code()'但沒有使用它。 – Frank

+1

另外,我認爲擴展std名稱空間的方式會導致未定義的行爲:https://stackoverflow.com/questions/41062294/c-when-is-it-ok-to-extend-the-std-namespace,http: //en.cppreference.com/w/cpp/language/extending_std – KjMag

+0

@Frank根據教程,我不應該需要它?也許我在誤讀它。 – ruipacheco

回答

1

這工作:

#include <system_error> 
#include <string> 

namespace my_project { 
    enum class my_error { 
    warning = 45836431 
    }; 
} 

namespace std { 
    // you had a typo here, and you defined a different std::my_error class 
    template <> 
    struct is_error_code_enum<my_project::my_error> : public true_type {}; 
} 

namespace my_project { 

    namespace internal { 
    struct my_error_category : public std::error_category { 
     const char* name() const noexcept override { 
     return "AAA"; 
     } 
     std::string message(int ev) const noexcept override { 
     const std::string message = "BBB"; 
     return message; 
     } 
    }; 
    } 

inline std::error_code make_error_code(const my_project::my_error &e) { 
    return {static_cast<int>(e), my_project::internal::my_error_category()}; 
}; 
} 

int main() 
{ 
    std::error_code ec = my_project::my_error::warning; 
} 

鏘的錯誤消息,讓我在正確的軌道上,因爲它爲什麼沒有使用正確的告訴我構造函數。