代码之家  ›  专栏  ›  技术社区  ›  Mikhail T.

如何在私有类成员上使用decltype?

  •  0
  • Mikhail T.  · 技术社区  · 6 年前

    private:
        array<double, 9>         foo;
    public:
        const array<double, 9> & getFoo() const { return foo; }
        void                     setFoo(const array<double, 9> & _foo) { foo = _foo; }
    

    我真的很想去 必须不断重复 array<double, 9> 其他地方——使用 decltype 引用字段的类型,不管它是什么。

    不幸的是 decltype(instance.foo) 不在课外工作,因为 foo 是私人的。

    decltype(getFoo()) 几乎 作品-- getFoo 是公共的,并且必须具有相同的类型。

    遗憾的是,上述“差不多”还不够好-- 格特福 参考文献 ( array<double, 9> & ).

    如何在类之外的代码中获取实际类型,以便调用setter函数:

      SOMETHING values;
      for (auto &i : values)
          i = something();
      instance.setFoo(values);
    
    3 回复  |  直到 6 年前
        1
  •  3
  •   Jarod42    6 年前

    你可以用 decltype 使用类型修饰符:

    std::decay_t<decltype(instance.getFoo())> values; // std::array<double, 9>
    for (auto &i : values)
        i = something();
    instance.setFoo(values);
    
        2
  •  6
  •   AndyG    6 年前

    使用 type alias .

    class Foo
    {
        public:
            using array_t =          std::array<double, 9>; 
        private:
            array_t                  foo;
        public:
            const array_t  &         getFoo() const { return foo; }
            void                     setFoo(const array_t & _foo) { foo = _foo; }
    };
    

    允许您将类型提供给用户,并且允许您不必键入 std::array<double, 9> . 您还可以只在一个地方更改类型。

    Foo::array_t bar;
    
        3
  •  1
  •   463035818_is_not_an_ai    6 年前

    代码中几乎没有上下文,但通常您只需根据它们的含义命名,例如:

    struct my_image {
        typedef std::array<int,900> raw_image_t;
        const raw_image_t& get_raw(){ return data;}
    private:
        raw_image_t data;
    };
    

    my_image::raw_image_t x = f.get_raw();