Given an arbitrary numeric type which may or may not be a std::complex type, I’d like to get the type that represents the “real part” of that type. For example, the real part of std::complex<double> is double, and the real part of double is double itself. The example below uses C++ partial template specialization to accomplish this. @mfontanini has posted an even simpler method below.
My question: is there a direct way of doing this that is already available in the Boost library? If so, I have been unable to find it.
#include <complex>
#include <boost/type_traits/is_complex.hpp>
template <typename T>
class RealPart
{
private:
template <bool, typename>
class ResultType;
// complex type -> real type
template <typename T1>
class ResultType<true, T1>
{
public:
typedef typename T1::value_type type;
};
// real type -> real type
template <typename T1>
class ResultType<false, T1>
{
public:
typedef T1 type;
};
public:
// define result_type, making use of the template specialization above
typedef typename ResultType<boost::is_complex<T>::value, T>::type result_type;
};
// both will become doubles
RealPart<std::complex<double> > a;
RealPart<double> b;
There’s no need to use type traits, you can accomplish the same using only template specialization:
Whether this is already implemented somewhere in boost, I don’t really know.