Std::clamp equivalent?

Is there a std::clamp equivalent for c++11? I found that vexcode pro doesn’t use c++17 in this post, but not if there was a equivalent.

There isn’t an easy clamp function, but you can make your own very simply. If you wanted to clamp between 1 and -1 you can use a few if statements. Check if its between 1 and -1 if its larger then clamp to 1 and if its less than -1 clamp to -1.

you can always just write your own clamp function. The code below should work for any data type with an overloaded < and > operator.

template<typename T>
T clamp(T val, T mn, T mx){
return std::max(std::min(val, mx), mn);
}

5 Likes