Thursday, 15 July 2010

templates - How do I determine an arbitrary C++ numeric type's real part's type? -



templates - How do I determine an arbitrary C++ numeric type's real part's type? -

given arbitrary numeric type may or may not std::complex type, i'd type represents "real part" of type. example, real part of std::complex<double> double, , real part of double double itself. illustration below uses c++ partial template specialization accomplish this. @mfontanini has posted simpler method below.

my question: there direct way of doing available in boost library? if so, have been unable 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 utilize of template specialization above typedef typename resulttype<boost::is_complex<t>::value, t>::type result_type; }; // both become doubles realpart<std::complex<double> > a; realpart<double> b;

there's no need utilize type traits, can accomplish same using template specialization:

// general case template <typename t> struct realpart { typedef t type; }; // std::complex template <typename t> struct realpart<std::complex<t> > { typedef t type; };

whether implemented somewhere in boost, don't know.

c++ templates

No comments:

Post a Comment