Templated class: Check if complex at compile time

后端 未结 1 699
渐次进展
渐次进展 2021-01-22 17:59

I have a class A templated with a Scalar which can be real- or complex-valued. It has a method realPart which is supposed to return the re

相关标签:
1条回答
  • 2021-01-22 18:29

    This can be done with a simple is_complex trait and SFINAE:

    template<class T> struct is_complex : std::false_type {};
    template<class T> struct is_complex<std::complex<T>> : std::true_type {};
    
    template<class Scalar>
    class A {
    public:
        A(const Scalar z) : z_(z)
        { }
    
        template<class S = Scalar, std::enable_if_t<is_complex<S>{}>* = nullptr>
        Scalar realPart()
        {
          return z_.real();
        }
    
        template<class S = Scalar, std::enable_if_t<!is_complex<S>{}>* = nullptr>
        Scalar realPart()
        {
          return z_;
        }
    private:
        Scalar z_;
    };
    
    0 讨论(0)
提交回复
热议问题