Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Const receiving a var, i cant pass it to a template

Tags:

c++

What I want to do is:

int const bitsPerInt = log2(X);
bitset<bitsPerInt>  bits(a random number...);

but I get this error:

'bitsPerInt' cannot appear in a constant expression error: template argument 1 is invalid

like image 866
reinaldomoreira Avatar asked Mar 20 '23 04:03

reinaldomoreira


1 Answers

If you really need this to work, make your own log2 that works in compile-time and pass it to bitset's template argument.

constexpr unsigned Log2(unsigned n, unsigned p = 0) {
    return (n <= 1) ? p : Log2(n / 2, p + 1);
}

constexpr size_t bitCount = Log2(X);
std::bitset<bitCount> bits;

Live example.


Here's the solution using template meta-programming i.e. without using constexpr:

template<int N,unsigned int P=0>
struct Log2 { enum { value = Log2<N/2,P+1>::value }; };

template <unsigned p>
struct Log2<0, p> { enum { value = p }; };

template <unsigned p>
struct Log2<1, p> { enum { value = p }; };

std::bitset<Log2<4>::value> bits;

Live example.

This version should work in both C++03 and C++11; however, if you've access to C++11, I'd still recommend the constexpr way since it's cleaner (easier to understand).

like image 170
legends2k Avatar answered Mar 31 '23 20:03

legends2k