Search code examples
c++exception

Alternative way to mark a noexcept function as not implemented


I like to do this if I have only written an empty or partial implementation of a function:

... foo(...)
{
    // Some unfinished implementation or empty

    throw std::runtime_error("Not implemented.");
}

, so that I won't forget to complete the implementation before using it . And the code can compile and will work fine so long as I don't use it.

However, this will cause the compiler to give either a warning or an error if foo() has noexcept. Is there an alternative yet elegant way to achieve this?


Solution

  • You could always terminate the program:

    #include <exception>
    #include <iostream>
    #include <source_location>
    
    [[noreturn]] void Unimplemented(
        std::source_location caller,
        std::source_location called = std::source_location::current()) noexcept {
        std::cerr << "Unimplemented function\n"
                  << called.file_name() << '(' << called.line()
                  << "): " << called.function_name() << "\ncalled from\n"
                  << caller.file_name() << '(' << caller.line()
                  << "): " << caller.function_name() << '\n';
        std::terminate();
    }
    
    void foo(std::source_location loc = std::source_location::current()) noexcept {
        Unimplemented(loc);
    }
    
    int main() {
        foo(); 
    }
    

    Possible output:

    Unimplemented function
    /app/example.cpp(15): void foo(std::source_location)
    called from
    /app/example.cpp(19): int main()