Templated class: Check if complex at compile time

后端 未结 1 701
渐次进展
渐次进展 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 struct is_complex : std::false_type {};
    template struct is_complex> : std::true_type {};
    
    template
    class A {
    public:
        A(const Scalar z) : z_(z)
        { }
    
        template{}>* = nullptr>
        Scalar realPart()
        {
          return z_.real();
        }
    
        template{}>* = nullptr>
        Scalar realPart()
        {
          return z_;
        }
    private:
        Scalar z_;
    };
    

    0 讨论(0)
提交回复
热议问题