How to c++ check in noexcept that the template parameter T defined through template will throw or not throw an exception during the operation+.
In fact, you need to check the addition T + T for throwing a possible exception. I wrote the following code: noexcept(T + T)
, but, unfortunately, such code does not compile.
Asked
Active
Viewed 260 times
0

Tippa Toppa
- 21
- 1
-
Which version of C++ are you asking about? – Nicol Bolas Jan 26 '22 at 15:54
-
2What you did in your previous question (`noexcept(std::declval
() + std::declval – user17732522 Jan 26 '22 at 15:58())`) should compile. There might be issues with it for testing only rvalue or only lvalue operands, but I don't see why you changed it? -
```noexcept(std::declval
() + std::declval – Tippa Toppa Jan 26 '22 at 16:00())``` is correct code? I'm in training on how to do this check. But, unfortunately, the system does not accept my answer, so I doubted this code. -
@TippaToppa Yes, it is valid code and you also used it in a correct way in your previous question. What is "the system"? Do you mean you got a compilation error with it? – user17732522 Jan 26 '22 at 16:02
2 Answers
3
T + T
is not a valid expression. T
is a type, and types do not have operators. What you want are objects of type T
and to add them together to see if that expression is noexcept
or not. You can do that like
noexcept(std::declval<T>() + std::declval<T>())

NathanOliver
- 171,901
- 28
- 288
- 402
-
Note that `noexcept` is applied to functions. Which typically have parameters. Which typically have names that `noexcept` can already access. And typically, these parameters will involve at least one which is of type `T`. So `declval` is almost always unnecessary. – Nicol Bolas Jan 26 '22 at 16:00
3
If you're using C++20, you can write a concept to check this:
template<class T>
concept noexcept_addable = requires(T a)
{
requires noexcept(a + a);
};
Note that it's requires noexcept(a + a);
, not just noexcept(a + a);
. The latter would just check that noexcept(a + a);
is valid to compile, whereas the former actually requires that it evaluates to true
.
You can see a demo of this concept here.

Nathan Pierson
- 5,461
- 1
- 12
- 30