17

Are noexcept specifiers accepted in function typedefs?

as in:

 typedef void (*fptr)()  noexcept;

Intuitively, noexcept specifiers seem to make sense since they would allow some optimisations at the caller's side.

I got a mixed answer from gcc 4.6.1.

 typedef void (*fptr)()  noexcept;

results in: error: ‘fptr’ declared with an exception specification

but:

template<void (*FPtr)()  noexcept>
struct A{};

compiles without warning.

mirk
  • 5,302
  • 3
  • 32
  • 49
  • 1
    In C++17 and later, exception specifications (aka. `noexcept`) are allowed in (member) function types as well as in function pointer and reference types. – Quirin F. Schroll Sep 14 '22 at 12:13

1 Answers1

10

clang gives:

test.cpp:1:25: error: exception specifications are not allowed in typedefs
typedef void (*fptr)()  noexcept;
                        ^
1 error generated.

This is backed up in the C++11 standard in 15.4 [except.spec]/p2:

... An exception-specification shall not appear in a typedef declaration or alias-declaration.

Howard Hinnant
  • 206,506
  • 52
  • 449
  • 577
  • Thanks. This probably makes accepting the noexcept-clause in the template-argument above a bug in gcc? – mirk Oct 26 '11 at 16:54
  • 2
    I don't think so. [temp.param]/p4 says that non-type parameters can be a pointer to function and I don't see any mention of exception-specifications in that area. And [except.spec]/p2 specifically says that an exception-specification can appear on a pointer to function. – Howard Hinnant Oct 26 '11 at 17:13
  • Thanks again. I am a bit puzzled with this outcome, but there is no point in arguing with the standard. – mirk Oct 27 '11 at 09:48
  • @DirkM: The same problems were present with the `throw()` specifier, see [here](http://www.gotw.ca/publications/mill22.htm) for a nice example. – Xeo Oct 27 '11 at 12:25
  • @Xeo: indeed. I checked and `trow()` is accepted at exactly the same spots as `noexcept` – mirk Oct 27 '11 at 12:53
  • 1
    @DirkM: Maybe because both are exception specifications? ;) – Xeo Oct 27 '11 at 12:53
  • 2
    Note that one can still declare a typedef for a noexcept function pointer: `void dummy() noexcept; typedef decltype(dummy)* f_ptr_t;`. Working code can be found [here](https://ideone.com/Z0gMd9). – Max Truxa Aug 14 '15 at 08:59