Is it possible to declare a function pointer including the throw specification? For example, I have this function:
void without_throw() throw() {
}
And would like to to create a function that accepts it as a parameter, complete with the throw()
part. I've tried adding it to the typedef
, but that doesn't seem to work:
typedef void (*without)() throw();
GCC gives me the error error: ‘without’ declared with an exception specification
.
You can't typedef that. It's explicitly not allowed in the standard. (And replacing that with noexcept
doesn't help, same problem.)
Quoting C++11 draft n3290 (§15.4/2 Exception specifications)
An exception-specification shall appear only on a function declarator for a function type, pointer to function type, reference to function type, or pointer to member function type that is the top-level type of a declaration or definition, or on such a type appearing as a parameter or return type in a function declarator. An exception-specification shall not appear in a typedef declaration or alias-declaration. [ Example:
void f() throw(int); // OK void (*fp)() throw (int); // OK void g(void pfa() throw(int)); // OK typedef int (*pf)() throw(int); // ill-formed
– end example]
The second example allows you to do something like this:
void foo() throw() {}
void bar() {}
int main()
{
void (*fa)() throw() = foo;
void (*fb)() throw() = bar; // error, does not compile
}
Also you can use std::function if c++0x is acceptable:
#include <functional>
void without_throw() throw() {}
typedef std::function<void() throw()> without;
int main()
{
without w = &without_throw;
w();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With