Skip to content

Commit b73dcdf

Browse files
authored
Merge pull request #293 from Ivorforce/complex-select
Add xtl::select overload for complex values.
2 parents c52350e + fa4a43a commit b73dcdf

2 files changed

Lines changed: 39 additions & 0 deletions

File tree

include/xtl/xcomplex.hpp

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -106,6 +106,23 @@ namespace xtl
106106
template <class E, class R = void>
107107
using enable_scalar = std::enable_if_t<xtl::is_arithmetic<E>::value, R>;
108108

109+
/*************************
110+
* select implementation *
111+
*************************/
112+
113+
// Complex overload of xtl::select (see xfunctional.hpp, which covers
114+
// scalars only): at least one of v1 / v2 is complex, the other may be a
115+
// scalar.
116+
template <class B, class T1, class T2,
117+
XTL_REQUIRES(std::is_scalar<B>,
118+
std::disjunction<is_gen_complex<T1>, is_gen_complex<T2>>,
119+
std::disjunction<std::is_scalar<T1>, is_gen_complex<T1>>,
120+
std::disjunction<std::is_scalar<T2>, is_gen_complex<T2>>)>
121+
inline std::common_type_t<T1, T2> select(const B& cond, const T1& v1, const T2& v2) noexcept
122+
{
123+
return cond ? v1 : v2;
124+
}
125+
109126
/*******************
110127
* common_xcomplex *
111128
*******************/

test/test_xcomplex.cpp

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -328,5 +328,27 @@ namespace xtl
328328
EXPECT_COMPLEX_APPROX_EQ(b / x_closure, b / 5.0);
329329
EXPECT_COMPLEX_APPROX_EQ(x_closure / b, 5.0 / b);
330330
}
331+
332+
TEST(xcomplex, select)
333+
{
334+
std::complex<double> a(1., 2.);
335+
std::complex<double> b(3., 4.);
336+
EXPECT_EQ(select(true, a, b), a);
337+
EXPECT_EQ(select(false, a, b), b);
338+
339+
// Mixed precision promotes to the common type.
340+
std::complex<float> af(1.f, 2.f);
341+
EXPECT_EQ(select(true, af, b), std::complex<double>(1., 2.));
342+
EXPECT_EQ(select(false, af, b), b);
343+
344+
// Mixed real / complex.
345+
EXPECT_EQ(select(true, 5., b), std::complex<double>(5., 0.));
346+
EXPECT_EQ(select(false, 5., b), b);
347+
348+
xcomplex<double> xa(1., 2.);
349+
xcomplex<double> xb(3., 4.);
350+
EXPECT_EQ(select(true, xa, xb), xa);
351+
EXPECT_EQ(select(false, xa, xb), xb);
352+
}
331353
}
332354

0 commit comments

Comments
 (0)