On forcing all derived classes to implement a specific non-virtual method, part 2 -- Raymond Chen
Building on the previous article, Raymond Chen explores how deleted functions can produce clearer compiler errors when derived classes fail to implement required non-virtual methods. He also examines C++26’s new custom diagnostic messages for deleted functions, their compiler support, and why this technique works in C++/WinRT but not C++/WRL.
On forcing all derived classes to implement a specific non-virtual method, part 2
by Raymond Chen
From the article:
Last time, we observed that one way to force all derived classes to implement a specific non-virtual method is simply not to implement it in the base class and sit back and wait for the compile-time fireworks. I noted that we can do better than this, though.
The problem is that the compiler tells you what is wrong, but the details are often buried in the “supplementary error information”, and it may not be obvious how to dig it out, or maybe you dig it out but you don’t understand how to fix it.
You can steer people to the correct error by implementing the method as deleted.
// C++/WRL struct OneWayConverter { // Derived classes must implement Convert() HRESULT STDMETHODCALLTYPE Convert(IInspectable* value, ABI::Windows::UI::Xaml::Interop::TypeName targetType, IInspectable* parameter, HSTRING language, IInspectable** result) = delete; // One-way converters cannot convert back HRESULT STDMETHODCALLTYPE ConvertBack(IInspectable* /*value*/, ABI::Windows::UI::Xaml::Interop::TypeName /*targetType*/, IInspectable* /*parameter*/, HSTRING /*language*/, IInspectable** result) { *result = nullptr; return E_NOTIMPL; } }; // C++/WinRT struct OneWayConverter { // Derived classes must implement Convert() winrt::Windows::Foundation::IInspectable Convert( winrt::Windows::Foundation::IInspectable const& /*value*/, winrt::Windows::UI::Xaml::Interop::TypeName const& /*targetType*/, winrt::Windows::Foundation::IInspectable const& /*parameter*/, winrt::hstring const& /*language*/) = delete; // One-way converters cannot convert back winrt::Windows::Foundation::IInspectable ConvertBack( winrt::Windows::Foundation::IInspectable const& /*value*/, winrt::Windows::UI::Xaml::Interop::TypeName const& /*targetType*/, winrt::Windows::Foundation::IInspectable const& /*parameter*/, winrt::hstring const& /*language*/) { throw winrt::hresult_not_implemented(); } }; // Plain C++ analogous scenario struct OneWayConverter { // Derived classes must implement Convert() Color Convert(Widget const& /*value*/) = delete; // One-way converters cannot convert back Widget ConvertBack(Color const& /*color*/) { throw std::exception("not implemented"); } };This has a few benefits.