0

I have tried to solve this, but I can't. I have a class definition and I want a member function (siz) to return a constant value to another member function (abc). This value is used as maximum index in an array declaration in that function. But this doesn't seems to work. Here is a simplified version:

class bin {
    constexpr int siz();
public:
    void abc();
};

constexpr int bin::siz() {
    const int sizz = sizeof(int) * 8;
}

void bin::abc() {
    char arr[siz()];   // compiler: this expression didn't evaluate as constant (¿?)
};

However, this other very similar code (but using simple functions) does compile...

constexpr int siz() {
    const int sizz = sizeof(int) * 8;
    return sizz;
}

int main() {
    char arr[siz()];
    return 0;
}
Anselmo GPP
  • 425
  • 2
  • 21
  • 3
    `constexpr int bin::siz()` is a function, so it must return a result, doesn't it? I do not see `return` statement. – 273K Apr 29 '18 at 03:31
  • Yes, I oversimplificated there. But the original code has the return statements, so they are not the problem. – Anselmo GPP Apr 29 '18 at 05:29

1 Answers1

2

I am not entirely sure but I think the problem is that in bin::abc, the object can be anything at run time. Hence, bin::siz() cannot be evaluated at compile time.

The following works fine

int main()
{
   bin b;
   char arr[b.siz()];
}

after changing bin to:

class bin {
public:
    constexpr int siz();
};

constexpr int bin::siz() {
    return sizeof(int) * 8;
}

If siz does not depend on the state of the object, as in your posted code, I suggest making it a static member function.

The following works fine for me.

class bin {
  public:
    static constexpr int siz();
    void abc() const;
};

constexpr int bin::siz() {
  return sizeof(int) * 8;
}

void bin::abc() const {
  char arr[siz()];
}

int main()
{
  bin b;
  char arr[b.siz()];
}
R Sahu
  • 204,454
  • 14
  • 159
  • 270
  • Yeah, it worked just by putting static to siz. Thank you very much! I supposse that the creation of an object of type bin implies that it's not posible to have a constant member function. However, this problems make me feel that sometimes I have limited my freedom (in some way). What if I want an array that could be created and initialized many times, with different sizes (different indexes)? The rules say the value for that index must be constant... – Anselmo GPP Apr 29 '18 at 05:40