Skip to content
Snippets Groups Projects
Unverified Commit 25939173 authored by René Fritze's avatar René Fritze
Browse files

[math] clamp now also works for known vector types

parent 101c1413
No related branches found
No related tags found
No related merge requests found
......@@ -35,6 +35,7 @@
#include <dune/xt/common/reenable_warnings.hh>
#include <dune/xt/common/type_traits.hh>
#include <dune/xt/common/vector.hh>
#include <dune/common/deprecated.hh>
namespace Dune {
......@@ -177,11 +178,23 @@ protected:
//! \return var bounded in [min, max]
template <typename T>
T clamp(const T var, const T min, const T max)
typename std::enable_if<!is_vector<T>::value, T>::type clamp(const T var, const T min, const T max)
{
return (var < min) ? min : (var > max) ? max : var;
}
template <typename T>
typename std::enable_if<is_vector<T>::value, T>::type clamp(const T var, const T min, const T max)
{
auto result = var;
std::size_t idx = 0;
for (auto&& element : var) {
result[idx] = clamp(element, min[idx], max[idx]);
++idx;
}
return result;
}
/**
* \returns: -1 iff val < 0
* 0 iff val == 0
......
......@@ -19,27 +19,39 @@
#include <dune/xt/common/ranges.hh>
using namespace Dune::XT::Common;
typedef testing::Types<double, int, Dune::FieldVector<double, 3>, std::vector<double>> ClampTestTypes;
typedef testing::Types<double, int> TestTypes;
typedef testing::Types<std::complex<double>, double, int> ComplexTestTypes;
template <typename T>
static typename std::enable_if<is_vector<T>::value, T>::type init_bound(int val)
{
const auto size = VectorAbstraction<T>::has_static_size ? VectorAbstraction<T>::static_size : 3u;
return VectorAbstraction<T>::create(size, val);
}
template <typename T>
static typename std::enable_if<!is_vector<T>::value, T>::type init_bound(int val)
{
return T(val);
}
template <class T>
struct ClampTest : public testing::Test
{
const T lower;
const T upper;
ClampTest()
: lower(T(-1))
, upper(T(1))
: lower(init_bound<T>(-1))
, upper(init_bound<T>(1))
{
}
};
TYPED_TEST_CASE(ClampTest, TestTypes);
TYPED_TEST_CASE(ClampTest, ClampTestTypes);
TYPED_TEST(ClampTest, All)
{
EXPECT_EQ(clamp(TypeParam(-2), this->lower, this->upper), this->lower);
EXPECT_EQ(clamp(TypeParam(2), this->lower, this->upper), this->upper);
EXPECT_EQ(clamp(TypeParam(0), this->lower, this->upper), TypeParam(0));
EXPECT_EQ(clamp(init_bound<TypeParam>(-2), this->lower, this->upper), this->lower);
EXPECT_EQ(clamp(init_bound<TypeParam>(2), this->lower, this->upper), this->upper);
EXPECT_EQ(clamp(init_bound<TypeParam>(0), this->lower, this->upper), init_bound<TypeParam>(0));
}
template <class T>
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment