简体   繁体   中英

noexcept operator compile-time check

In bellow code I'm trying to use conditional exception specification for functions but compile fails, although if used outside function it works just fine.

void may_throw();

// ERROR: expression must have bool type or be convertible to bool
void check () noexcept(may_throw());

int main()
{
    // works just fine!
    std::cout << noexcept(may_throw());
}

The question is how to check if function throws without changing function prototype to conditionally specify noexcept ?

I can't change function prototype because the point is to check if function throws not if it should return true or false.

EDIT

I'm trying to make fun of the noexcept but it looks like it's not working for macros.

#include <iostream>

#if 0
#define ASDF(...) (void)0
#else
#define ASDF(...) throw 1
#endif

void check() noexcept(noexcept(ASDF()))
{
    // wrong!
    // std::cout << noexcept(noexcept(ASDF()));

    // edit: it should be this, and it works.
    // (tnx: StoryTeller-UnslanderMonica)
    std::cout << noexcept(ASDF());
    ASDF(0);
}

int main()
{
    check();
}

Given void check () noexcept(may_throw()); , noexcept specifier expects an expression convertible to bool , while may_throw() returns void and can't convert to bool .

You should apply noexcept operator on may_throw() and specify it to noexcept specifier. ie

// whether check is declared noexcept depends on if the expression
// may_throw() will throw any exceptions
void check () noexcept(noexcept(may_throw()));
//            ^^^^^^^^          -> specifies whether check could throw exceptions 
//                     ^^^^^^^^ -> performs a compile-time check that returns true if may_throw() is declared to not throw any exceptions, and false if not.

The correct way to do it is:

noexcept( noexcept( may_throw() ) )

As to why, the first noexcept is defined as noexcept-specifier . This is used to tell whether a function is noexcept or not. It has the form (from [except.spec] ):

noexcept-specifier:
    noexcept ( constant-expression )
    noexcept
    throw ( )

The second, is the noexcept-operator : The noexcept operator determines whether the evaluation of its operand, which is an unevaluated operand (8.2), can throw an exception (18.1). from [expr.unary.noexcept]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM