1

I'm not sure why the array creation in the function passes but not the one in the class even though array size is a compile time computable value.

template<int N>
int getPow()
{
     int power = 1;
     while(power < N)
         power <<= 1;
     return power;
}

template<int N>
class Test
{
    private:
        int data[getPow<N>()];
};

void testfun()
{
    int test[getPow<2>()]; // passes
    Test<10> t1; // Fails????
}
5
  • 2
    What are you actually expecting power <<= 1; to do` Also that's not a constexpr. Commented Mar 18, 2019 at 20:53
  • @πάνταῥεῖ I am pretty sure OP is expecting the value to shift by 1 :), like sum += 1 Commented Mar 18, 2019 at 20:54
  • You have an easily fixable incorrect birwise shift operator, and in order to use result of this function as a size of array, you need to mark function constexpr. Commented Mar 18, 2019 at 20:55
  • You need to throw a constexpr in there to commit that it is, in fact, a compile-time value. Commented Mar 18, 2019 at 20:55
  • 0 Compiler does not allow that: "fields must have a constant size: 'variable length array in structure' extension will never be supported" Commented Mar 18, 2019 at 21:12

1 Answer 1

5

As getPow is not constexpr, it cannot be used in places which require constant expression (as C-array size).

int test[getPow<2>()]; // passes . You unfortunately use VLA extension. It should not pass.

You might solve your issue with:

template <unsigned N>
constexpr unsigned getPow()
{
     return 1 << N;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.