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

问题描述 投票:0回答:3

我有一个班级有一些“毛茸茸的”私人领域。每个都有访问器功能(getter和setter)。

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是公开的,必须具有相同的类型。

不幸的是,上面的“差不多”还不够好 - getFoo的类型实际上是一个参考(array<double, 9> &)。

如何获取类外部代码中的实际类型,以便我可以调用setter-function:

  SOMETHING values;
  for (auto &i : values)
      i = something();
  instance.setFoo(values);
c++ c++11 typeof decltype
3个回答
2
投票

您可以将decltype与类型修饰符一起使用:

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

7
投票

使用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;

1
投票

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

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();
© www.soinside.com 2019 - 2024. All rights reserved.