0

I am having some trouble wrapping my head around noexcept.

template <int SIZE>
int pop(int idx) noexcept(noexcept(SIZE > 0)) // this is what I dont understand
{
  if (idx <= 0)
    throw std::out_of_range("My array doesnt go that high");
  return idx;
}

This is just a simple function, but you see how it only throws an exception when idx <= 0, I dont understand. So in my specification, noexcept(idx > 0), I am trying to tell the compilier this function ONLY throws no exceptions if idx > 0. Am I doing this right?

Any help is appreciated, I hope I am explaining it right. Just some simple explanation would be great.

bryan sammon
  • 7,161
  • 15
  • 38
  • 48
  • In case anyone else has same problem, K-ballo response helped, and also, http://en.cppreference.com/w/cpp/language/noexcept_spec really helps – bryan sammon Jun 06 '12 at 02:57

1 Answers1

4

Actually the noexept specification expects a constant expression, not a runtime expression. You have used the noexcept specificatiom together with the noexcept operator. noexcept(idx >0) returns true as comparing two integers does not throw, and you are using that true as the argument to the noexcept specification telling the compiler your function never throws. The declaration

int pop(int idx) noexcept(noexcept(idx > 0))

says this function does not throw as long as idx > 0 does not throw, which is always the case for an int.

Update: Now you've changed the code in the question so that idx is a non-type template argument, however the same reasoning applies. Comparing ints never throws.

What you seem to be trying to do cannot be done in C++. That is, specify whether a function throws or not based on its runtime arguments.

K-ballo
  • 80,396
  • 20
  • 159
  • 169
  • Thanks for the help. I think you know what I am talking about though. Can you post an agreeable example? – bryan sammon Jun 06 '12 at 02:02
  • @bryan sammon: What you seem to be trying to do cannot be done in _C++_. That is, specify whether a function throws or not based on its runtime arguments. – K-ballo Jun 06 '12 at 02:02
  • Actually its all just new to me, just trying to learn noexcept specifications. Even if it is a compile time constant. I just put that example there to have a example. – bryan sammon Jun 06 '12 at 02:05
  • 1
    @bryan sammon: The `noexcept` _operator_ returns `false` if any of the operations could throw, it does not consider the values of the arguments themselves but only each of the functions/expressions involved. The `noexcept` _specification_ with a `true` argument indicates that a function does not throw. – K-ballo Jun 06 '12 at 02:08
  • well said, now that is what I was looking for, thanks alot man – bryan sammon Jun 06 '12 at 02:09