Search code examples
c++c++11typeofdecltype

How to use decltype on private class-members?


I have a class with some "hairy" private fields. There are accessor-functions (getters and setters) for each.

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

I'd really like to not have to keep repeating the array<double, 9> elsewhere -- using decltype to refer to the type of the field, whatever it might be.

Unfortunately, simply invoking decltype(instance.foo) does not work outside the class, because foo is private.

Fortunately, decltype(getFoo()) almost works -- getFoo is public and has to have the same type.

Unfortunately, the above "almost" is not good enough -- getFoo's type is actually a reference (array<double, 9> &).

How do I get the actual type in the code outside of the class so that I can, for example, call the setter-function:

  SOMETHING values;
  for (auto &i : values)
      i = something();
  instance.setFoo(values);

Solution

  • You might use decltype with type modifier:

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