NotImplementedException C++

NotImplementedException C++

根据回答here我实现了我的classNotImplementedException

//exceptions.h
namespace base
{
    class NotImplementedException : public std::logic_error
    {
    public:
        virtual char const* what() { return "Function not yet implemented."; }
    };
}

在另一个 class 中,我想抛出以下异常(相同的命名空间):

    std::string to_string() override
    {
        throw NotImplementedException();
    }

to_string 方法是来自抽象基础 class 的重写方法。

namespace BSE {
    class BaseObject
    {
        virtual std::string to_string() = 0;
    };
}

不幸的是,前面代码的编译显示了这个错误:

error C2280: BSE::NotImplementedException::NotImplementedException(void)': attempting to reference a deleted function`

来自 I understood that the problem it has something to do with move constructor or assignment which according to cppreference.com - throw (1) 可能是这种情况:

First, copy-initializes the exception object from expression (this may call the move constructor for rvalue expression, and the copy/move may be subject to copy elision)

我试过添加

    NotImplementedException(const NotImplementedException&) = default;
    NotImplementedException& operator=(const NotImplementedException&) = default;

我的 class 但这给了我

error C2512: 'BSE::NotImplementedException': no appropriate default constructor available

据我所知 std::logic_error 没有定义默认构造函数。

:我该如何解决这个问题?

应该是这样的:

namespace base
{
    class NotImplementedException : public std::logic_error
    {
    public:
        NotImplementedException () : std::logic_error{"Function not yet implemented."} {}
    };
}

然后

std::string to_string() override
{
    throw NotImplementedException();
}

不说明未实现的异常非常烦人,所以我会这样做:

namespace base
{
    class NotImplementedException : public std::logic_error
    {
    public:
        using logic_error::logic_error;
         
        NotImplementedException(
                const std::source_location location = std::source_location::current())
            : logic_error{std::format("{} is not implemented!", location.function_name())}  
       {}
    };
}

然后

std::string to_string() override
{
    throw NotImplementedException("to_string for object");
    // or using source_location:
    throw NotImplementedException();
}

C++20 的特性对于这种情况很酷,但不是强制性的(并且在大多数编译器上仍然不可用)。

一些demo