Handling gcc's noexcept-type warning
There's several things you can do about the warning message.
Disable it with -Wno-noexcept-type
. In many projects the warning message is unhelpful because there's no chance the resulting object will be linked with an another object that expects it to use GCC's C++17 name mangling. If you're not compiling with different -std=
settings and you're not building a static or shared library where the offending function is part of its public interface then the warning message can safely disabled.
Compile all your code with -std=c++17
. The warning message will go away as the function will use the new mangled name.
Make the function static
. Since the function can no longer be referenced by another object file using a different mangling for the function the warning message will not be displayed. The function definition will have to be included in all compilation units that use it, but for template functions like in your example this is common anyways. Also this won't work for member functions were static
means something else.
When calling a function template specify the template parameter explicitly giving a compatible function pointer type that doesn't have the exception specification. For example call<void (*)()>(func)
. You should also be able to use cast to do this as well, but GCC 7.2.0 still generates a warning even though using -std=c++17
doesn't change the mangling.
When the function isn't a template don't use noexcept
with any function pointer types used in the function's type. This and the last point rely on the fact that only non-throwing function pointer types result in naming mangling changes and that non-throwing function pointers can be assigned (C++11) or implicitly converted (C++17) to possibly throwing function pointers.
I'm upvoting Ross's answer for the call<void (*)()>(func)
solution. It explicitly tells the compiler that you want the template instantiated for a non-noexcept
function type, and guarantees that your code will operate exactly the same in C++17 as it did in C++14.
More alternatives are:
(1) Wrap the noexcept
function in a lambda (which isn't noexcept
):
template <class Func>
void call(Func f)
{
f();
}
void func() noexcept { }
int main()
{
call([]() { func(); });
}
(2) Create a separate wrapper function without noexcept
. This is more typing initially, but if you have multiple call sites it could save typing overall. This is what I ended up doing in the code that originally prompted me to file the GCC bug.