c++c++20c++-conceptsrequires-clause

C++ Add constraints to a noexcept member function of template class


I have a 3D vector template class and I want to add a normalize member function to it.

Normalizing a vector only makes sense, if they use floating point numbers.

I want to use the c++20 requires syntax with the std::floating_point concept.

template<typename Type>
class vector3 {

  [...]

  vector3& normalize() requires std::floating_point<Type> noexcept;

}

But the compiler (gcc 11.2.0) gives me an error

error: expected ';' at end of member declaration
  242 |   vector3& normalize() requires (std::floating_point<Type>) noexcept;
      |                                                          ^
      |                                                          ;

Solution

  • noexcept is part of declarator, and requires-clause must come after declarator (dcl.decl)

    so you need to write

    // from @Osyotr in comment
    vector3 & normalize() noexcept requires std::is_floating_point_v<Type>;