Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I put a throw declaration in a typedef function signature?

Tags:

c++

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.

like image 754
edA-qa mort-ora-y Avatar asked Nov 10 '14 07:11

edA-qa mort-ora-y


2 Answers

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
}
like image 189
Mat Avatar answered Oct 16 '22 02:10

Mat


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();
}
like image 29
Levon Avatar answered Oct 16 '22 04:10

Levon