3

So I wrote this code ->

#include <iostream>
#include <bitset>

int main(){

    int num, temp, digits = 0;
    std::cin >> num;
    temp = num;

    while(temp){
        temp /= 10;
        ++digits;
    }

    const int size = digits;

    std::bitset<size> a(num);
    std::cout << a << std::endl;

    return 0;
}

The bitset container isnt accepting the const integer size as a parameter and throwing an error -Non-type template argument is not a constant expression. I want to know why this is happening as size has been declared as a constant and it's value isnt gonna change during the run-time of my program ?

Robert Andrzejuk
  • 5,076
  • 2
  • 22
  • 31
Shubham Anand
  • 128
  • 10
  • Possible duplicate of [Difference between \`constexpr\` and \`const\`](https://stackoverflow.com/questions/14116003/difference-between-constexpr-and-const) – LogicStuff Aug 05 '17 at 08:22
  • Use `constexpr` instead of `const` for size. You can also put the code that calculate the size in a `constexpr` function. – Guillaume Racicot Aug 05 '17 at 16:47

1 Answers1

5

A const variable can be interpreted differently, depending on what is assigned to it.

  1. When assigned a compile time constant: it will be a compile time constant. That means that during compilation the constant value can be directly used in-place.

  2. When assigned from another variable (which is not a compile time constant) : the new variable is unmodifilable. In that sense the variable is not a compile time constant. It cannot be modified in that block of code.

A template requires a compile time constant.

Robert Andrzejuk
  • 5,076
  • 2
  • 22
  • 31
  • Can you please explain 2 more? In my case the other variable is also a constant int literal, passed as argument. I also get the same error as OP. Can you post some references for your answer? – Ariel Lubonja Oct 01 '22 at 01:27
  • 1
    @ArielLubonja please make a new post for your question. But you cannot use a function argument as a compile time constant! It is just impossible. You need to do it another way. – Robert Andrzejuk Oct 01 '22 at 16:21