4

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?

Scheff's Cat
  • 19,528
  • 6
  • 28
  • 56
Michał Turek
  • 701
  • 3
  • 21
  • A function either throws or not. You can condition `noexcept` on how different **types** behave, not the **values** of those types – Alexey S. Larionov Sep 09 '21 at 11:30
  • I'm reading Scott Mayer's effective modern c++, and he says that they can be noexcept in some certain ranges. But He didnt say much about this specification, that's why I'm asking about it. – Michał Turek Sep 09 '21 at 11:32

1 Answers1

8

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.

463035818_is_not_an_ai
  • 109,796
  • 11
  • 89
  • 185