1

I'm trying to use static array which size needs to be determined by given template values. However size will be constant across program runtime - thats why I decided not to use std::vector.

template<uint32_t BAR_WIDTH>
class Bar 
{
//do_stuff...
Foo mapper[ [&]()->int{ uint32_t tmp = BAR_WIDTH / Foo:FOO_EDGE; return (BAR_WIDTH % 10 == 0) ? tmp : tmp + 1; }; ];
};

FOO_EGDE is const static value. IDE gives me a hint that

Array size expression must have an integer type instead of int(*)()

I wonder if I can make it work this way without using std::vector. Any advice is welcomed and appreciated.

412131
  • 91
  • 6
  • 3
    The error message is telling you the problem - your array size isn't an integer, it's a lambda taking no arguments and returning `int`. – Chowlett Aug 16 '17 at 08:10

2 Answers2

3

The problem is, that you are using a lambda for determining the size of the array. If you leave it off and just use the ternary operator, it works:

int main() {
    const bool z = true;
    const int x = 5, y = 3;
    int arr[z ? x : y];
    return 0;
}

Ideone

As opposed to:

int main() {
    const bool z = true;
    const int x = 5, y = 3;
    int arr[[&]() -> int { return z ? x : y; }];
    return 0;
}

Ideone

Post Self
  • 1,471
  • 2
  • 14
  • 34
2

As described here, lambda expressions can't be constexpr yet, and you can only declare the size of an array with a constexpr value (even then, you are not trying to invoke declared lambda (to invoke it - () is required at the end of declaration).

To work around such problem, you could use a private static constexpr method, and use the return value of it, for the array size declaration:

static constexpr uint32_t GetArraySize ()
    {
    uint32_t tmp = BAR_WIDTH / Foo::FOO_EDGE;
    return (BAR_WIDTH % 10 == 0) ? tmp : tmp + 1;
    }

Foo mapper[GetArraySize ()];
Algirdas Preidžius
  • 1,769
  • 3
  • 14
  • 17