Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Specifying noexcept function conditionally

Tags:

c++

noexcept

Let's say I have such function declared noexcept:

int pow(int base, int exp) noexcept
{
    return (exp == 0 ? 1 : base * pow(base, exp - 1));
}

From my very little, but slowly growing knowledge of C++, I can noexcept when I'm certain that function will not throw an exception. I also learned that it can be in some range of values, lets say that I consider my function noexcept when exp is smaller than 10, and base smaller than 8 (just as an example). How can I declare that this function is noexcept in such a range of values? Or the most I can do is leave a comment for other programmers that it should be within some certain ranges?

like image 437
Michał Turek Avatar asked Jan 25 '23 06:01

Michał Turek


1 Answers

You can use a condition for noexcept, but that condition must be a constant expression. It cannot depend on the value of parameters passed to the function, becaue they are only known when the function is called.

From cppreference/noexcept:

Every function in C++ is either non-throwing or potentially throwing

It cannot be both nor something in between. In your example we could make base a template parameter:

template <int base>
int pow(int exp) noexcept( base < 10)
{
    return (exp == 0 ? 1 : base * pow<base>(exp - 1));
}

Now pow<5> is a function that is non-throwing, while pow<10> is a function that is potentially throwing.

like image 170
463035818_is_not_a_number Avatar answered Feb 07 '23 11:02

463035818_is_not_a_number