Tippa Toppa
Tippa Toppa

Reputation: 21

How to check in c++ noexcept(T + T), where T is template

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.

Upvotes: 0

Views: 682

Answers (2)

Nathan Pierson
Nathan Pierson

Reputation: 5565

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.

Upvotes: 3

NathanOliver
NathanOliver

Reputation: 180945

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>())

Upvotes: 3

Related Questions